Js trunk difference between getters and direct access to model attributes

what is the advantage / reason for using backbone-js for syntax

//using a Model instance called model model.get('attribute') 

but not

 model.attribute 

I'm just starting to use the trunk, and I always try to access attributes directly

+8
javascript
source share
2 answers

If you look at the source code, the get function simply calls this.attributes[name] .

http://backbonejs.org/docs/backbone.html#section-31

The advantage, however, is at least twice:

1) a compatible API that reduces the amount of code you write

2) the ability to override the get method and provide more complex access control

For example, there are several plug-ins for the trunk that redefine the operation of models to provide the capabilities of nested models. it’s very easy for them to let you write the get method as follows:

model.get("submodel.attr")

and analyze attr submodel submodels. Without the get method, it would be harder to do this according to the API.

The main advantage of this is encapsulation. Until JavaScript provides true get / set properties that allow us to write code for getters and seters, we will stick to working methods such as Backbone get and set .

+12
source share

Well .. for starters model.attribute absolutely NOT right. model.set() is required to trigger change events. You will most likely forget about it if you get used to using model.attributes[attribute] instead of model.get(attribute)

+2
source share

All Articles