Computed Properties
JSData supports computed properties. When you define a computed property you also define the fields that it depends on. The computed property will only be updated when one of those fields changes. DS#createInstance
will update computed properties once, but the computed properties of an item will only continue to be updated if the item was actually injected into the data store.
Computed properties using change detection
var store = new JSData.DS();
var User = store.defineResource({
name: 'user',
computed: {
// each function's argument list defines the fields
// that the computed property depends on
fullName: ['first', 'last', function (first, last) {
return first + ' ' + last;
}],
// shorthand, use the array syntax above if you want
// your computed properties to work after you've
// minified your code. Shorthand style won't work when minified
initials: function (first, last) {
return first.toUppercase()[0] + '. ' + last.toUppercase()[0] + '.';
}
}
});
var user = User.inject({
id: 1,
first: 'John',
last: 'Anderson'
});
user.fullName; // "John Anderson"
user.first = 'Fred';
// js-data relies on dirty-checking, so the
// computed property (probably) hasn't been updated yet
user.fullName; // "John Anderson"
// If your browser supports Object.observe this will have no effect
// otherwise it will trigger the dirty-checking
store.digest();
user.fullName; // "Fred Anderson"
Computed properties using property accessors
var store = new JSData.DS();
var User = store.defineResource({
name: 'user',
computed: {
// object passed to Object.defineProperty
fullName: {
// default is false
enumerable: true,
get: function () {
return this.first + ' ' + this.last;
}
},
initials: {
get: function () {
return this.first.toUppercase()[0] + '. ' + this.last.toUppercase()[0] + '.';
}
}
}
});
var user = User.inject({
id: 1,
first: 'John',
last: 'Anderson'
});
// executes the getter to retrieve the value
user.fullName; // "John Anderson"
user.first = 'Fred';
// executes the getter to retrieve the value
user.fullName; // "Fred Anderson"
Additional reading:
Need help?
Want more examples or have a question? Post on the Slack channel or mailing list then we'll get your question answered and probably update this wiki.
Updated less than a minute ago