I've really grown to love computed properties in Ember.js. What would be the closest implementation of computed properties in node.js?
EDIT: Should have been a bit more precise. The cool features on embers computed properties are
All this results in object definitions which are more like declarations, with little functional code but contain a lot of functionality.
You can use standard getters / setters (available in almost every JS environment).
var person = {
firstName: 'Mike',
lastName: 'C',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName(val) {
var valArray = val.split(/\s/);
this.firstName = valArray[0];
this.lastName = valArray[1];
return val;
}
};
console.log(person.fullName); // Mike C
person.lastName = 'Myers';
console.log(person.fullName); // Mike Myers
person.fullName = 'John Doe';
console.log(person.firstName); // John
What sets frameworks like Ember and KnockoutJS apart from vanilla JS (which is all Node.js has plus some APIs for things like I/O) is their ability to handle dependency tracking. Dependency tracking is not provided out of the box. There was a proposal for Object.observe
which would allow for dependency tracking (which you'd still have to do some work yourself) but has since been removed from the standard so don't plan on using it.
Take a look at Object.defineProperies
or Object.definePropery
. They will allow you to define a getter and setter for a property of an object.
var person = { first: 'John', last: 'Doe' };
Object.defineProperty(person, 'fullName', {
get: function(){ return this.first + ' ' + this.last },
set: function(val){
var pair = val.split(/\s/);
this.first = pair[0];
this.last = pair[1];
return val;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.