Reputation: 97
I have a object when any of the value to the keys inside the object changes I want to update a computed property. Is there a way to observe the value changes of an object with computed property.
Upvotes: 1
Views: 5095
Reputation:
Computed properties and observers are two different things. Computed properties automatically "observe" specified properties and recompute themselves lazily when needed. Observers are used less frequently when you want to perform some action immediately when a property changes. In your case, you seem to want something like this in your model. If it is indeed a DS.Model
as it appears to be, then you can use isDirty
. If you'd prefer to put this in the controller, use model.isDirty
(or in most recent versions of Ember Data model.hasDirtyAttributes
) instead:
updateServer: function() {
if (!this.get('isDirty')) return;
pingServer();
}.observes('isDirty')
If you want to have a computed property which is recomputed whenever any of the model properties change, you can list isDirty
as a dependency. This is an example of a controller property:
canSave: function() {
return this.get('isEditing') && this.get('model.isDirty');
}.property('isEditing', 'model.isDirty')
and then, for example
<button class="{{if canSave 'active'}}">Save</button>
The button will be automatically made active (via the active
CSS class) whenever the user is in editing mode and the model is dirty.
The isDirty
flag is cleared when the model is saved. If you are not saving the model, but want to clear the isDirty
flag, you can do
If you want to observe all property changes on a non-DS.Model
object, or observe changes to your own defined properties on the model (as opposed to DS.*
type properties), then this is a hard problem to solve. Ember provides no out-of-the-box solution. You can Google for "observe changes to Ember object properties", or review the question proposed as a duplicate.
Upvotes: 4
Reputation: 1264
You can define computed properties in your model like so :
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string')
/* COMPUTED */
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}.property('firstName', 'lastName')
});
You can now use your new fullName
property and it will be magically updated whenever the firstName
or lastName
changes.
UPDATE
In order to poke your server when something changes, you could do something like that in your ObjectController:
changesObserver: function() {
// this will be called everytime one of the attribute is changed
// so you could do your server post here I guess
Ember.$.ajax(/*...*/);
}.observes('attributeA', 'attributeB', etc)
Upvotes: 0