If I am using Backbone, which (or both) of these is the “correct” way to set data?
// Logic in the Model
// Can call from anywhere that has access
SomeModel = Backbone.Model.extend({
defaults: {
visible: false
},
toggle: function(visible){
visible = typeof visible !== "undefined" ? visible : !this.get("visible");
this.set({visible: visible});
}
});
OR
// Logic in the View
SomeView = Backbone.View.extend({
events: {
"click .toggle" : "toggleVisibility"
},
toggleVisibility: function(){
this.model.set({visible: !this.model.get("visible")});
}
});
Obviously either one of these work, but my question is how much of that logic should be pushed off to the model? If, for instance, I have a situation that updates two variables:
this.model.set({visible: false, foo: bar, something: else});
Would it make sense to create a function on the model like this:
someFunction: function(visible, foo, something){
this.set({visible: visible, foo: foo, something: something});
}
That just seems like overkill to me, but the set({}) logic in the view feels dirty.
Thoughts?
It seems that you’re mixing view logic into your models which isn’t really a great idea. I would imagine there is some data in your model that is relevant to whether the view that has it bound should be visible (something like deleted: true, etc.) but you should toggle visibility based on that attribute changing. I would envision something like:
That way all your view logic is in your view and not your model. The model is empty since backbone has no need to define a schema, but generally you’ll add functionality there at some point.