Reputation: 1572
I have problem with function each.In my console is error:
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 });
I can't find error nowhere. My json file:
[
{"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}
]
I wanna render all my objects from collection, and after that I wanna add event to add next table after click. But my problems is why this is not function ?
Upvotes: 0
Views: 2248
Reputation: 14501
Render doesn't have the correct context.
this.collection.on('reset', this.render);
this.collection.on('add', this.addOne, this );
You need to add the context parameter (third parameter).
this.collection.on('reset', this.render, this);
Upvotes: 4