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!
The Backbone. js Views specify how your data looks like. They represent model's data to the users. They can be used with any JavaScript template library. They handle users input events, bind events and methods, render model and collection and interact with users.
Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).
js (aka Backbone) is designed to add structure to client-side applications, to avoid a spaghetti-code mess. In the words of Backbone. js: Backbone.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With