Backbone - Cannot call method 'each' of undefined
我的每个功能都有问题。在我的控制台中出现错误:
未捕获的类型错误:无法调用未定义的方法 \\'each\\'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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 文件:
1 2 3 4 5 6 7 | [ {"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} ] |
我想从集合中渲染我的所有对象,然后我想添加事件以在单击后添加下一个表。但我的问题是为什么这不起作用?
渲染没有正确的上下文。
1 2 | this.collection.on('reset', this.render); this.collection.on('add', this.addOne, this ); |
需要添加上下文参数(第三个参数)。
1 | this.collection.on('reset', this.render, this); |