0

我正在编写一个backbone.js 应用程序,但我遇到了问题。我的收藏不会触发事件,任何人都可以在下面的代码中发现问题吗?我得到了渲染反馈,初始化器反馈..但是永远不会调用 append 方法。我知道“../app”返回一个带有 tro json 项目的列表。我什至可以看到这些是在集合中创建的。为什么我的事件没有被调用?

window.TablesInspectorView = Backbone.View.extend({

    tagName: "div",

    initialize: function () {
        console.log('Initializing window.TablesInspectorView');        

        // setup the tables
        this.data     = new Backbone.Collection();
        this.data.url = "../app";
        this.data.fetch();

        // some event binds..
        this.data.on("change", this.render     , this);
        this.data.on("add"   , this.append_item, this);
    },
    render: function(){
        console.log("render");
        _.each(this.data.models, this.append_item);
    },
    append_item: function(item) {
        console.log("appended");
    }
});
4

1 回答 1

2

According to my knowledge , the backbone fetch() is an asynchronous event and when it completes the reset event is triggered ,

When the models belonging to the collection (this.data) are modified , the change event is triggered, so im guessing you have not got that part correct.

so i would do something like this :

window.TablesInspectorView = Backbone.View.extend({

    tagName: "div",

    initialize: function () {
        console.log('Initializing window.TablesInspectorView');        

        // setup the tables
        this.data     = new Backbone.Collection();
        this.data.url = "../app";
        this.data.fetch();

        // some event binds..
        this.data.on("reset", this.render     , this); //change here
        this.data.on("add"   , this.append_item, this); // i dont see a this.data.add() in you code so assuming this was never called ?
    },
    render: function(){
        console.log("render");
        _.each(this.data.models, this.append_item);
    },
    append_item: function(item) {
        console.log("appended");
    }
});
于 2013-02-07T19:09:38.527 回答