主干集合未触发添加事件

Backbone Collection Not firing Add Event

本文关键字:添加 事件 集合      更新时间:2023-09-26

所以我有一个问题,我有一个主干集合,用于创建函数以将数据保存到 REST API。数据将保存到服务器,并将模型添加到当前集合,但随后不会触发集合的 add 事件。以下是代码片段视图初始化函数

intialize : function() {
        this.listenTo(this.collection, 'add', this.updateList);
    },      

updateList 函数仅执行控制台日志。使用集合保存数据的视图函数为:

cards = this.collection;
        debugger
        cards.create(data, {
            success : function(model, response) {
                console.log("success on saving card");
                console.log(response);
                console.log("Updating list");
                console.log(cards);
            },
            error : function(model, response) {
                console.log("error on saving card");
                console.log(model);
                console.log("response");
                console.log(response);
            }
        })
        return false;

在视图中尝试以下代码:

initialize: function() {
    this.collection.on('add', this.updateList, this);
}

或:

var someCollection = new SomeCollection();
var view = new SomeView({collection: someCollection});
view.listenTo(someCollection, 'add', view.updateList);

你为什么不直接使用: this.model.on('change', doAction, this); 在视图中? 如果我理解正确,这是一个更好的解决方案,因为您的模型正在发生变化。另外,我找不到任何地方强制使用 On() 函数 ListenTo(),你能告诉我你在哪里看到它吗?