I have a view which doesn’t seem to want to render as the model’s change event is not firing.
here’s my model:
var LanguagePanelModel = Backbone.Model.extend({
name: "langpanel",
url: "/setlocale",
initialize: function(){
console.log("langselect initing")
}
})
here’s my view:
var LanguagePanelView = Backbone.View.extend({
tagName: "div",
className: "langselect",
render: function(){
this.el.innerHTML = this.model.get("content");
console.log("render",this.model.get(0))
return this;
},
initialize : function(options) {
console.log("initializing",this.model)
_.bindAll(this, "render");
this.model.bind('change', this.render);
this.model.fetch(this.model.url);
}
});
here’s how I instantiate them:
if(some stuff here)
{
lsm = new LanguagePanelModel();
lsv = new LanguagePanelView({model:lsm});
}
I get logs for the init but not for the render of the view?
Any ideas?
I guess it’s about setting the attributes of the model – name is not a standard attribute and the way you’ve defined it, it seems to be accessible directly by using
model.nameand backbone doesn’t allow that AFAIK. Here are the changes that work 🙂 You can see the associated fiddle with it too 🙂UPDATE:
You don’t need to manually trigger the change event – think of it as bad practice. Here’s what the backbone documentation says (note: fetch also triggers change!)
Fetch
So, if the value fetched from the server is different from the defaults the change event will be fired so you needn’t do it yourself. If you really wish to have such an event then you can use the trigger approach but custom name it since it’s specific to your application. You are basically trying to overload the event so to speak. Totally fine, but just a thought.
Change
The change event is to be manually triggered only if you’ve been suppressing the event by passing
silent:trueas an argument to thesetmethod of the model.You may also want to look at ‘has changed‘ and other events from the backbone doc.
EDIT Forgot to add the updated fiddle for the above example – you can see that the alert box pops up twice when the model is changed by explicitly calling
set– the same would happen on fetching too. And hence the comment on the fact that you “may not” need to trigger ‘change’ manually as you are doing 🙂