Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone js difference between getters vs direct access of model attributes

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

like image 673
Pete_ch Avatar asked Mar 19 '12 00:03

Pete_ch


2 Answers

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.

like image 65
Derick Bailey Avatar answered Oct 20 '22 15:10

Derick Bailey


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)

like image 27
Scott Evernden Avatar answered Oct 20 '22 15:10

Scott Evernden