【问题标题】:Backbone Collection Not firing Add Event骨干收集未触发添加事件
【发布时间】:2013-09-27 17:13:12
【问题描述】:

所以我有一个问题,我有一个骨干集合,用于创建函数以将数据保存到 REST API。数据被保存到服务器,模型被添加到当前集合,但是没有触发集合的添加事件。下面是代码的 sn-ps 视图初始化函数

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

updateList函数只做一个控制台日志。使用集合保存数据的views函数是:

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;

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    在您的视图中尝试此代码:

    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);
    

    【讨论】:

    • 我试过了,但没用,所以我不知道是什么问题。我正在使用骨干网 1.0,它建议使用 listenTo() 而不是 on
    • 您在骨干文档中看到的地方,它建议使用listenTo() 而不是on()?文档说:The advantage of using this form, instead of on(), is that listenTo() allows the object to keep track of the events,and they can be removed all at once later on - 这与您在之前的评论中写的不同。
    • 尝试将console.log('event is fired); 添加到您的回调函数中...请查看我的更新代码。
    • 是的,很抱歉,这只是一个建议,我已经从这个问题开始着手,显然它开始独立工作,我还不知道出了什么问题。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      相关资源
      最近更新 更多