Are you initializing Backbone views from a model or elsewhere?

Are you initializing Backbone views from a model or elsewhere?

I am trying to figure out what is the best way to organize the model / views. Does it make sense for your models to initialize views?

Thanks for any info!

+6
source share
2 answers

Model

No, your models do not initialize other MVVM objects.
Make sure that they are only responsible for determining the data that they will wear and how they will be stored.

var CoolModel = Backbone.Model.extend({ defaults: function() { return { coolness: 'extreme', color: 'red' }; } }; var myModel = new CoolModel; 

View

Your views should contain an initialization function that will be called automatically using 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 go through the model to which it is attached. And this can happen anywhere in your code (but usually at the application level):

 renderSomething: function(todo) { var view = new CoolView({model: myModel}); // view.render() .... } 

That is, your application combines a model and a view.

+12
source

Although this is certainly not a complete and complete answer, I would recommend that you read Backbone Todos Annotated Docs .

You will see that they listen to the “add” event in the collection and create a view for the new model from the main view when it is added to the collection. You can see this in the AppView initialization function in annotated documents.

This is also the way I do this for all my applications, and this is what I would recommend. This approach also allows you to include more logic around the new model if you need to (for example, re-rendering a statistics profile that keeps track of the number of models in the collection).

+3
source

All Articles