数据绑定-在Javascript中数组改变时更新有序列表

data binding - Update ordered list when array changes in Javascript

本文关键字:更新 列表 改变 数组 Javascript 数据绑定      更新时间:2023-09-26

所以我已经使用了很多Backbone和Angular,并习惯了在这些生态系统中进行数据绑定/视图更新,但我不知道如何在纯JS中实现这一点(没有框架/库)。

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

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功能添加一个回调,但如果我要添加更多功能来操作我的列表,它似乎不能很好地扩展。我已经阅读了一些关于观察者模式的内容,但不确定这是否真的是我在这里寻找的。

您不希望将回调传递给每次调用ContactList。push和ContactList。删除和所有的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 */
};

此解决方案不允许您动态地将订阅者添加到Contact List的更改事件中,但它可能是一个有用的起点。