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!
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.