like everything else in software development, "it depends."
if you use form inputs in your views, and you just need to get data from these inputs in the model, set the data directly. You can do this in any number of ways, including "changing" events from input fields, for example:
MyView = Backbone.View.extend({ events: { "change #name", "setName" }, setName: function(e){ var val = $(e.currentTarget).val(); this.model.set({name: val}); } });
On the other hand, if you are starting a business logic and other code that allows you to set data in a model (but actually it is only done as part of the business logic), you must call the method on the model.
The state machine will be a good example of when you do this. Or, in the image gallery I wrote, I had some logic around choosing an image to display. If an image has already been selected, do not select it again. I applied this logic in the method of my image model:
Image = Backbone.Model.extend({ select: function(){ if (!this.get("selected")){ this.set({selected: true}); } } });
As shown here, I like to work by a simple rule: if I have zero logic around the call for dialing, I install it directly from where I am. If there is any logic associated with the model around the set, then I put it in the model.
In any case, when you want to set the data, you should use the set
method. Bypassing this and setting model attributes directly through model.attributes
prevent a lot of Backbone code from running and could potentially cause problems for you.
source share