0

我正在开发一个 Backbone.js 项目,我对 collection.on 或所谓的绑定感到很困惑。

这是我的视图中的一些代码。

initialize: function(){
        this.accCollection = this.options.accCollection;
        //Nothing shows without this line, which renders 3 times
        this.accCollection.on('all', this.render, this); 
        this.accCollection.fetch({
            success:function(){
                this.render;  
            }
        });
    },

    render: function(){
        $('.currentPage').html("<h3>Accounts</h3>");
        console.log(this.accCollection.models);
        //Render it in jade template  
        this.$el.html(this.template({accCollection:this.accCollection.models}));
        return this;
    }

所以我不明白的是为什么没有这条线它不会工作。如果我使用'all'和'add',它会起作用。是不是我的 fetch 导致它第一次不呈现空数据,而第二次第三次它工作,因为它已经被填满了?使困惑!

this.accCollection.on('all', this.render, this); 

告诉我是否需要提供更多信息,我将编辑问题!

/问候

4

1 回答 1

2

几件事:

  1. 在视图中,您应该this.listenTo(下面的示例):这确保当视图被销毁时事件被取消委托。
  2. 您的success回调不共享视图的上下文。this在您的回调中是指options您传入的对象,而不是视图甚至集合。

您可能想要做的是:

initialize: function(){
    this.accCollection = this.options.accCollection;
    this.listenTo(this.accCollection, 'reset', this.render, this); 
    // Setting reset to true will trigger the reset event
    this.accCollection.fetch({ reset: true });
}
于 2013-12-04T16:47:25.990 回答