Using Backbone i’m starting to build an App where i have everything cleanly separated. But now i have the following question. Where should i put the App main logic, in the views or in the model.
For example i have a view and a model, which are binded to a button and when i click that button i have to make
$.ajax(params)
do i put that in the view or the view calls a method with :
this.model.doAction(params)
which do you think is the best approach?
You can define an
eventsproperty in the view which is of the format{"event selector": "callback"}for eg.{"click .collapse": "collapse"}where collapse would be a function defined as a property of the view. Then write your ajax request code in this callback function.Also, unless I am missing something, “binding a view and model to a button” doesn’t sound correct Backbone way to me. Instead you should think of one instance of model associated with one instance of the view. Whenever an attribute of the the model instance changes, a model
changeevent will be triggered. You can bind a view function to this event so that change in the model is reflected in the view. Here is a quick exampleTo associate a model with a view instance, you can pass the it while instantiating a new
view object..
The set function call will fire change event and will result in render function of view
to be called.
Refer to the annotated source of Todos app example for a complete example.