what is the advantage/ reason for backbone-js to use the syntax
//using a Model instance called model
model.get('attribute')
and not
model.attribute
Im just starting to use backbone and I always ind myself trying to access the attributes directly
If you look at the source code, the get
function just calls to this.attributes[name]
.
http://backbonejs.org/docs/backbone.html#section-31
The benefit, though, is at least two-fold:
1) a consistent API that reduces the amount of code you are writing
2) the ability to override the get
method and provide more complex access control
For example, there are several plugins for backbone that override how models work in order to provide nested model capabilities. it's very easy for them to allow you to write a get method like this:
model.get("submodel.attr")
and have that parse out the attr
of the submodel
sub-model. Without the get method, it would be more difficult to make this consistent with the API.
The underlying benefit from this is encapsulation, though. Until JavaScript provides true get/set properties that let us write code for getters and setters, we'll be stuck with work-around methods like Backbone's get
and set
.
Well .. for starters, model.attribute
is absolutely NOT correct. model.set()
is required in order to get change
events to fire. You're very likely to forget this if you get in the habit of using model.attributes[attribute]
instead of model.get(attribute)
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