Do you initialize your Backbone views from within a model or elsewhere?
I'm trying to figure out what the best way to organize model/views. Does it make sense to have your models initialize the views?
Thanks for any info!
Do you initialize your Backbone views from within a model or elsewhere?
I'm trying to figure out what the best way to organize model/views. Does it make sense to have your models initialize the views?
Thanks for any info!
Share Improve this question edited Mar 29, 2013 at 16:41 boom asked Mar 29, 2013 at 16:37 boomboom 11.7k9 gold badges47 silver badges66 bronze badges 1- 2 The other way around is more mon and a model or collection knowing about the views smells bad. – mu is too short Commented Mar 29, 2013 at 16:48
2 Answers
Reset to default 12Model
No, your models don't initialize any other MVVM obects.
Make sure that they are only responsible for defining the data that they will carry, and how they will persist it.
var CoolModel = Backbone.Model.extend({
defaults: function() {
return {
coolness: 'extreme',
color: 'red'
};
}
};
var myModel = new CoolModel;
View
Your views should contain an initialize function that will get called automatically by the Backbone.View "parent":
var CoolView = Backbone.View.extend({
doSomething: function() { ... },
doSomethingElse: function() { ... },
initialize: function() {
this.listenTo(this.model, 'eventA', this.doSomething);
this.listenTo(this.model, 'eventB', this.doSomethingElse);
}
});
AppView
When you actually create a view object, you pass in the model it will be bound to. And that can technically happen anywhere in your code (but monly in the Application-level view):
renderSomething: function(todo) {
var view = new CoolView({model: myModel});
// view.render() ....
}
That is, your application brings together a model and a view.
While this is definately not a full and plete answer, I would remend you read through the Backbone Todos Annotated Docs.
You will see that what they do is listen to the 'add' event on the collection, and create the view for a new model from the main view when it is added to the collection. You can see this in the AppView initialize function in the annotated docs.
This is also the way I do it for all my apps, and is what I would remend. This approach also lets you include more logic around the new model if you need to (such as re-rendering a stats view which keeps track of the number of models in the collection).