Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中更改数组时更新有序列表_Javascript_Data Binding_Observer Pattern_Publish Subscribe - Fatal编程技术网

在Javascript中更改数组时更新有序列表

在Javascript中更改数组时更新有序列表,javascript,data-binding,observer-pattern,publish-subscribe,Javascript,Data Binding,Observer Pattern,Publish Subscribe,所以我已经使用了主干网和Angular,并且已经习惯了这些生态系统中的数据绑定/视图更新,但是我不知道如何在纯JS无框架/库中实现这一点 现在我有一个简单的用户列表,我想观察它的变化,并在发生时触发和更新无序列表 var ContactList = { list: [], push: function(obj) { this.storage.push(obj); }, remove: functon(obj) { return th

所以我已经使用了主干网和Angular,并且已经习惯了这些生态系统中的数据绑定/视图更新,但是我不知道如何在纯JS无框架/库中实现这一点

现在我有一个简单的用户列表,我想观察它的变化,并在发生时触发和更新无序列表

var ContactList = {
    list: [],
    push: function(obj) {
        this.storage.push(obj);
    },
    remove: functon(obj) {
        return this.storage.splice(this.storage.indexOf(obj), 1);
    }
};

var Contact = function(attributes) {
    this.attributes = attributes || {};
};

Contact.prototype.get = function(property) {
    return this.attributes[property];
};

Contact.prototype.set = function(property, value) {
    this.attributes[property] = value;
};

理想情况下,以下内容将自动添加到列表中。我可以在push和remove方法中添加回调,但是如果我在列表中添加了更多的方法,那么它的伸缩性似乎不太好。我已经阅读了一些关于observer模式的内容,但不确定这是否是我在这里寻找的内容。

您不想将回调传递给ContactList.push和ContactList.remove以及所有尚未编写的ContactList方法的每次调用。相反,联系人名单将知道他何时改变,然后向全世界宣布这一事实。在一个简单的实现中,ContactList可以拥有自己的onChange方法,他可以调用该方法:

var ContactList = {
    list: [],
    push: function (obj) {
        this.list.push(obj);
        this.onChange();
    },
    remove: function (obj) {
        var index = this.list.indexOf(obj);
        if (index > -1) {
            var removed = this.list.splice(index, 1);
            this.onChange();
            return removed;
        } else {
            return null;   
        }
    }
};
显然,您必须定义ConactList.onChange:

ContactList.onChange =  function () {
    console.log(this.list);
    /* update your ul element */
};
此解决方案不允许您将订阅者动态添加到联系人列表的更改事件中,但它可能是一个有用的起点