I would like to attach a new model to a view and have the view re-render. I’m able to render the view in the first place, but I’m having trouble changing the data in that view to a new model.
my_model_1 = Backbone.Model.extend({});
my_model_2 = Backbone.Model.extend({});
my_view = Backbone.View.extend({
initialize : function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
render : function(){
}
});
var view_instance = new my_view({ model: my_model_1 });
//Template gets rendered
try{
view_instance.changeModel(my_model_2);
}catch(e){console.log(e)};
try{
view_instance.set(my_model_2);
}catch(e){console.log(e)};
try{
view_instance.fetch(my_model_2);
}catch(e){console.log(e)};
try{
view_instance.model = my_model_2;
}catch(e){console.log(e)};
//Template should get updated with data from model 2
Any advice?
The
changeevent if fired when the data in your model has changed, in your case your view isn’t “rerenering” because the data of it’s model hasn’t changed rather you just switched models. What you can do is manually trigger the change event after switching your view’s model or call it’srendermethodFor example