0

我的每个功能都有问题。在我的控制台中是错误:

未捕获的类型错误:无法调用未定义的方法“每个”

window.App = {
    Models: {},
    Views: {},
    Collections: {}
};
window.template = function (id) {
    return _.template($('id' + id).html());
};
App.Models.Table = Backbone.Model.extend({
    defaults: {
            name: 'Table Name',
        },
});
App.Collections.Tables = Backbone.Collection.extend({
    model: App.Models.Table,
    url: 'tables.json'
});
App.Views.Tables = Backbone.View.extend({
    tagName: 'ul',
    initialize: function() {
        this.collection.fetch({reset:true});
        this.collection.on('reset', this.render);
        this.collection.on('add', this.addOne, this );
    },
    render: function () {
        this.collection.each(this.addOne, this);
        return this;
        },
    addOne: function(table) {
        var table = new App.Views.Table({ model: table });
        this.$el.append( table.render().el );
        table.render();
        }
});
App.Views.Table = Backbone.View.extend({
    tagName: 'li',
    initialize: function() {
      this.model.on('destroy', this.remove, this)  
    },
    render: function () {
        this.$el.html( this.model.get('name') );
        return this;
    },
});
var tablesCollection = new App.Collections.Tables();    
var tablesView = new App.Views.Tables({ collection: tablesCollection });

我无法在任何地方找到错误。我的 json 文件:

[
    {"name": "Table 1","stts": "redstts","id": 1},
    {"name": "Table 2","stts": "redstts","id": 2},
    {"name": "Table 3","stts": "redstts","id": 3},
    {"name": "Table 4","stts": "redstts","id": 4},
    {"name": "Table 5","stts": "redstts","id": 5}
]

我想从集合中渲染我的所有对象,然后我想添加事件以在单击后添加下一个表。但我的问题是为什么这不起作用?

4

1 回答 1

4

渲染没有正确的上下文。

this.collection.on('reset', this.render);
this.collection.on('add', this.addOne, this );

您需要添加上下文参数(第三个参数)。

this.collection.on('reset', this.render, this);
于 2013-09-19T01:19:58.453 回答