javascript - What does .property() do? in function(){}.property() -
todos.todocontroller = ember.objectcontroller.extend({ iscompleted: function(key, value){ var model = this.get('model'); if (value === undefined) { // property being used getter return model.get('iscompleted'); } else { // property being used setter model.set('iscompleted', value); model.save(); return value; } }.property('model.iscompleted') });
i'm working through todo guide ember.js , can't seem understand how controller works. .property() mean? , how come when remove 'return value;' line functionality stays same. if explain what's going on here great.
link guide: http://emberjs.com/guides/getting-started/marking-a-model-as-complete-incomplete/
in javascript way processing when getting or setting 1 property using object.defineproperty:
object.defineproperty(person, "b", { : function() { return person.firstname + ' ' + person.surname; }, set : function(newvalue) { var names = newvalue.split(' '); person.firsname = names[0]; person.surname = names[1]; }, enumerable : true, configurable : true });
but have disadvantages:
- isn't cross browser
- doesn't have binding, in other words, if
firstname
orsurname
changes, dependent propertyfullname
isn't changed. - calling
person.name
whenperson
undefined, make error throwed - isn't possible trigger observers, no without additional code , aware of depency hierachy:
firstname
dependsfullname
, , can dependency of others properties arghhh!
because ember have own concept of property, called computed property.
it can declared in 2 ways:
foo: ember.computed(function({ ... }).property(dependent keys);
or when using (the default) ember.env.extend_prototypes = true
:
foo: function() { ... }.property(dependent keys);
the property(dependent keys)
, needed because tell ember properies when changed, make property updated.
fullname: function(key, value) { // setter if (value !== undefined) { var names = value.split(' '); this.set('firstname', names[0]); this.set('surname', names[1]); } // return complete result, nexts calls this.get('fullname') return cached value return this.get('firstname') + ' ' + this.get('surname'); }.property('firstname', 'surname')
using this, have advantage of:
- when changing
firstname
orsurname
new value,fullname
changed. - the
beforeobserves
triggered before changing value, ,observes
triggered after value change. - any template referencing property updated
- more 1 call person.get('firstname'), return cached value, saving processing. can disable using
.property(..).volatile()
- avoid null or undefined errors, when accessing null objects like:
controller.get('person.dog.name')
returnsundefined
, if person or dog undefined.
i hope helps
Comments
Post a Comment