Reputation: 11666
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!
Upvotes: 6
Views: 6556
Reputation: 5480
While this is definately not a full and complete answer, I would recommend 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 recommend. 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).
Upvotes: 3
Reputation: 9133
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;
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);
}
});
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 commonly 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.
Upvotes: 12