Update a item from a list width Backbone.js
I've started using Backbone.js and i have an issue with the updating of html elements. This is my code:
Router:
App.Routers.Test = Backbone.Router.extend({
routes: {
"/start" : "start",
"/modify" : "modify"
},
start: function() {
this.List = new App.Collections.Test;
this.ViewList = new App.Views.Test({model: this.List});
this.List.fetch();
},
modify: function() {
var model = this.List.get(1);
model.set({name: 'Item modified'});
alert('Modified!');
}
});
Views:
App.Views.Item = Backbone.View.extend({
inizialize: function() {
this.model.bind('change:name',this.render);
},
render: function() {
$('#tmpl').开发者_Python百科tmpl(this.model.attributes).appendTo(this.el); // jQuery Template
return this;
}
});
App.Views.Test = Backbone.View.extend({
el: '#list',
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('reset', this.render);
},
render: function() {
$(this.el).empty();
this.model.each(function(model) {
var viewItem = new App.Views.Item({model: model});
$('#list').append((viewItem.render().el));
});
}
});
When I go to "#/modify" the Model has changed, but this not updated on the html view, although I have added in the item views this code:
this.model.bind('change:name',this.render);
Maybe I didn't understand the correct functioning of backbone, how to behave?
PS: Since I'm new on backbone, is accept any advice.
In your modify
method, call the appropriate view. I usually pass an instance of the model
and el
. So, for example:
this.modifyPage = new App.Views.Test({
el: $('#list'),
model: model
});
Though, if you don't need the el
as context from the router, it's best to limit the use of jQuery to only the views.
精彩评论