Class: SC.Observable

Key-Value-Observing (KVO) simply allows one object to observe changes to a property on another object. It is one of the fundamental ways that models, controllers and views communicate with each other in a SproutCore application. Any object that has this module applied to it can be used in KVO-operations.

This module is applied automatically to all objects that inherit from SC.Object, which includes most objects bundled with the SproutCore framework. You will not generally apply this module to classes yourself, but you will use the features provided by this module frequently, so it is important to understand how to use it.

Enabling Key Value Observing

With KVO, you can write functions that will be called automatically whenever a property on a particular object changes. You can use this feature to reduce the amount of "glue code" that you often write to tie the various parts of your application together.

To use KVO, just use the KVO-aware methods get() and set() to access properties instead of accessing properties directly. Instead of writing:

var aName = contact.firstName;
  contact.firstName = 'Charles';

use:

var aName = contact.get('firstName');
  contact.set('firstName', 'Charles');

get() and set() work just like the normal "dot operators" provided by JavaScript but they provide you with much more power, including not only observing but computed properties as well.

Observing Property Changes

You typically observe property changes simply by adding the observes() call to the end of your method declarations in classes that you write. For example:

SC.Object.create({
    valueObserver: function () {
      // Executes whenever the "Value" property changes
    }.observes('value')
  });

Although this is the most common way to add an observer, this capability is actually built into the SC.Object class on top of two methods defined in this mixin called addObserver() and removeObserver(). You can use these two methods to add and remove observers yourself if you need to do so at run time.

To add an observer for a property, just call:

object.addObserver('propertyKey', targetObject, targetAction);

This will call the 'targetAction' method on the targetObject to be called whenever the value of the propertyKey changes.

Observer Parameters

An observer function typically does not need to accept any parameters, however you can accept certain arguments when writing generic observers. An observer function can have the following arguments:

propertyObserver(target, key, value, revision);

Implementing Manual Change Notifications

Sometimes you may want to control the rate at which notifications for a property are delivered, for example by checking first to make sure that the value has changed.

To do this, you need to implement a computed property for the property you want to change and override automaticallyNotifiesObserversFor().

The example below will only notify if the "balance" property value actually changes:

automaticallyNotifiesObserversFor: function (key) {
    return (key === 'balance') ? NO : sc_super();
  },

  balance: function (key, value) {
    var balance = this._balance;
    if ((value !== undefined) && (balance !== value)) {
      this.propertyWillChange(key);
      balance = this._balance = value;
      this.propertyDidChange(key);
    }
    return balance;
  }

Implementation Details

Internally, SproutCore keeps track of observable information by adding a number of properties to the object adopting the observable. All of these properties begin with "_kvo_" to separate them from the rest of your object.

Defined in: observable.js

Since:
SproutCore 1.0

Field Summary

Instance Methods

Field Detail

isObservable Boolean
Walk like that ol' duck

Instance Method Detail

addObserver(key, target, method, context)

Adds an observer on a property.

This is the core method used to register an observer for a property.

Once you call this method, anytime the key's value is set, your observer will be notified. Note that the observers are triggered anytime the value is set, regardless of whether it has actually changed. Your observer should be prepared to handle that.

You can also pass an optional context parameter to this method. The context will be passed to your observer method whenever it is triggered. Note that if you add the same target/method pair on a key multiple times with different context parameters, your observer will only be called once with the last context you passed.

Observer Methods

Observer methods you pass should generally have the following signature if you do not pass a "context" parameter:

fooDidChange: function (sender, key, value, rev);

The sender is the object that changed. The key is the property that changes. The value property is currently reserved and unused. The rev is the last property revision of the object when it changed, which you can use to detect if the key value has really changed or not.

If you pass a "context" parameter, the context will be passed before the revision like so:

fooDidChange: function (sender, key, value, context, rev);

Usually you will not need the value, context or revision parameters at the end. In this case, it is common to write observer methods that take only a sender and key value as parameters or, if you aren't interested in any of these values, to write an observer that has no parameters at all.

Parameters:
key String
the key to observer
target Object
the target object to invoke
method String|Function
the method to invoke.
context Object
optional context
Returns:
SC.Object
self
addObservesHandler(observer, path)

Will add an observes handler to this object for a given property path.

In most cases, the path provided is relative to this object. However, if the path begins with a capital character then the path is considered relative to the window object.

Parameters:
observer Function
the function on this object that will be notified of changes
path String
a property path string
Returns:
Object
returns this
addProbe(key)

Allows you to inspect a property for changes. Whenever the named property changes, a log will be printed to the console. This (along with removeProbe) are convenience methods meant for debugging purposes.

Parameters:
key String
The name of the property you want probed for changes
allPropertiesDidChange()

Notifies observers of all possible property changes.

Sometimes when you make a major update to your object, it is cheaper to simply notify all observers that their property might have changed than to figure out specifically which properties actually did change.

In those cases, you can simply call this method to notify all property observers immediately. Note that this ignores property groups.

Returns:
SC.Observable
automaticallyNotifiesObserversFor(key)

Determines whether observers should be automatically notified of changes to a key.

If you are manually implementing change notifications for a property, you can override this method to return NO for properties you do not want the observing system to automatically notify for.

The default implementation always returns YES.

Parameters:
key String
the key that is changing
Returns:
Boolean
YES if automatic notification should occur.
beginPropertyChanges()

Begins a grouping of property changes.

You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call this method at the beginning of the changes to suspend change notifications. When you are done making changes, call endPropertyChanges() to allow notification to resume.

Returns:
SC.Observable
bind(toKey, target, method)

Manually add a new binding to an object. This is the same as doing the more familiar propertyBinding: 'property.path' approach.

Parameters:
toKey String
the key to bind to
target Object
target or property path to bind from
method String|Function
method for target to bind from
Returns:
SC.Binding
new binding instance
decrementProperty(key, increment)
Decrements the value of a property.
Parameters:
key String
property name
increment Number
the amount to decrement (optional)
Returns:
Number
new value of property
destroyObservable()
This method will destroy the observable.
Returns:
Object
this
didChangeFor(context, propertyNames)

didChangeFor is a very important method which allows you to tell whether a property or properties have changed.

The key to using didChangeFor is to pass a unique string as the first argument, which signals, "Has anything changed since the last time this was called with this unique key?" The string can be anything you want, as long as it's unique and stays the same from call to call.

After the key argument, you can pass as many property arguments as you like; didChangeFor will only return true if any of those properties have changed since the last call.

For example, in your view's update method, you might want to gate DOM changes (generally a slow operation) on whether the root values have changed. You might ask the following:

if (this.didChangeFor('updateOnDisplayValue', 'displayValue')) {
  // Update the DOM.
}

In another method on the same view, you might send an event if that same value has changed:

if (this.didChangeFor('otherMethodDisplayValue', 'displayValue')) {
  // Send a statechart action.
}

Each call will correctly return whether the property has changed since the last time displayDidChange was called with that key. The following sequence of calls will return the following values:

  • this.set('displayValue', 'value1');
  • this.didChangeFor('updateOnDisplayValue', 'displayValue');

    true;

  • this.didChangeFor('updateOnDisplayValue', 'displayValue'); false;
  • this.didChangeFor('otherMethodDisplayValue', 'displayValue'); true;
  • this.set('displayValue', 'value2');
  • this.didChangeFor('updateOnDisplayValue', 'displayValue'); true;
  • this.didChangeFor('updateOnDisplayValue', 'displayValue'); false;
  • this.didChangeFor('updateOnDisplayValue', 'displayValue'); false;
  • this.didChangeFor('otherMethodDisplayValue', 'displayValue'); false;
This method works by comparing property revision counts. Every time a property changes, an internal counter is incremented. When didChangeFor is invoked, the current revision count of the property is compared to the revision count from the last time this method was called.

Parameters:
context String|Object
a unique identifier
propertyNames String
one or more property names
endPropertyChanges()

Ends a grouping of property changes.

You can use this method to group property changes so that notifications will not be sent until the changes are finished. If you plan to make a large number of changes to an object at one time, you should call beginPropertyChanges() at the beginning of the changes to suspend change notifications. When you are done making changes, call this method to allow notification to resume.

Returns:
SC.Observable
get(key)

Retrieves the value of key from the object.

This method is generally very similar to using object[key] or object.key, however it supports both computed properties and the unknownProperty handler.

Computed Properties

Computed properties are methods defined with the property() modifier declared at the end, such as:

fullName: function () {
    return this.getEach('firstName', 'lastName').compact().join(' ');
  }.property('firstName', 'lastName')

When you call get() on a computed property, the property function will be called and the return value will be returned instead of the function itself.

Unknown Properties

Likewise, if you try to call get() on a property whose values is undefined, the unknownProperty() method will be called on the object. If this method returns any value other than undefined, it will be returned instead. This allows you to implement "virtual" properties that are not defined upfront.

Parameters:
key String
the property to retrieve
Returns:
Object
the property value or undefined.
getEach()

Convenience method to get an array of properties.

Pass in multiple property keys or an array of property keys. This method uses getPath() so you can also pass key paths.

Returns:
Array
Values of property keys.
getPath(path)

Navigates the property path, returning the value at that point.

If any object in the path is undefined, returns undefined.

Parameters:
path String
The property path you want to retrieve
hasObserverFor(key)

Returns YES if the object currently has observers registered for a particular key. You can use this method to potentially defer performing an expensive action until someone begins observing a particular property on the object.

Parameters:
key String
key to check
Returns:
Boolean
incrementProperty(key, increment)
Increments the value of a property.
Parameters:
key String
property name
increment Number
the amount to increment (optional)
Returns:
Number
new value of property
initObservable()

This method will register any observers and computed properties saved on the object. Normally you do not need to call this method yourself. It is invoked automatically just before property notifications are sent and from the init() method of SC.Object. You may choose to call this from your own initialization method if you are using SC.Observable in a non-SC.Object-based object.

This method looks for several private variables, which you can setup, to initialize:

  • _observers: this should contain an array of key names for observers you need to configure.

  • _bindings: this should contain an array of key names that configure bindings.

  • _properties: this should contain an array of key names for computed properties.

Returns:
Object
this
logProperty(propertyNames)
Logs the named properties to the console.
Parameters:
propertyNames String...
one or more property names
notifyPropertyChange(key, value)

Convenience method to call propertyWillChange/propertyDidChange.

Sometimes you need to notify observers that a property has changed value without actually changing this value. In those cases, you can use this method as a convenience instead of calling propertyWillChange() and propertyDidChange().

Parameters:
key String
The property key that has just changed.
value Object
The new value of the key. May be null.
Returns:
SC.Observable
observersForKey(key)

Returns an array with all of the observers registered for the specified key. This is intended for debugging purposes only. You generally do not want to rely on this method for production code.

Parameters:
key String
the key to evaluate
Returns:
Array
array of Observer objects, describing the observer.
propertyDidChange(key, value, _keepCache)

Notify the observer system that a property has just changed.

Sometimes you need to change a value directly or indirectly without actually calling get() or set() on it. In this case, you can use this method and propertyWillChange() instead. Calling these two methods together will notify all observers that the property has potentially changed value.

Note that you must always call propertyWillChange and propertyDidChange as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like.

Parameters:
key String
The property key that has just changed.
value Object
The new value of the key. May be null.
_keepCache Boolean
Private property
Returns:
SC.Observable
propertyWillChange(key)

Notify the observer system that a property is about to change.

Sometimes you need to change a value directly or indirectly without actually calling get() or set() on it. In this case, you can use this method and propertyDidChange() instead. Calling these two methods together will notify all observers that the property has potentially changed value.

Note that you must always call propertyWillChange and propertyDidChange as a pair. If you do not, it may get the property change groups out of order and cause notifications to be delivered more often than you would like.

Parameters:
key String
The property key that is about to change.
Returns:
SC.Observable
registerDependentKey(key, dependentKeys)

Use this to indicate that one key changes if other keys it depends on change. Pass the key that is dependent and additional keys it depends upon. You can either pass the additional keys inline as arguments or in a single array.

You generally do not call this method, but instead pass dependent keys to your property() method when you declare a computed property.

You can call this method during your init to register the keys that should trigger a change notification for your computed properties.

Parameters:
key String
the dependent key
dependentKeys Array|String
one or more dependent keys
Returns:
Object
this
removeObserver(key, target, method)

Remove an observer you have previously registered on this object. Pass the same key, target, and method you passed to addObserver() and your target will no longer receive notifications.

Parameters:
key String
the key to observer
target Object
the target object to invoke
method String|Function
the method to invoke.
Returns:
SC.Observable
receiver
removeObservesHandler(observer, path)

Will remove an observes handler from this object for a given property path.

In most cases, the path provided is relative to this object. However, if the path begins with a capital character then the path is considered relative to the window object.

Parameters:
observer Function
the function on this object that will be notified of changes
path String
a property path string
Returns:
Object
returns this
removeProbe(key)
Stops a running probe from observing changes to the observer.
Parameters:
key String
The name of the property you want probed for changes
set(key, value)

Sets the key equal to value.

This method is generally very similar to calling object[key] = value or object.key = value, except that it provides support for computed properties, the unknownProperty() method and property observers.

Computed Properties

If you try to set a value on a key that has a computed property handler defined (see the get() method for an example), then set() will call that method, passing both the value and key instead of simply changing the value itself. This is useful for those times when you need to implement a property that is composed of one or more member properties.

Unknown Properties

If you try to set a value on a key that is undefined in the target object, then the unknownProperty() handler will be called instead. This gives you an opportunity to implement complex "virtual" properties that are not predefined on the object. If unknownProperty() returns undefined, then set() will simply set the value on the object.

Property Observers

In addition to changing the property, set() will also register a property change with the object. Unless you have placed this call inside of a beginPropertyChanges() and endPropertyChanges(), any "local" observers (i.e. observer methods declared on the same object), will be called immediately. Any "remote" observers (i.e. observer methods declared on another object) will be placed in a queue and called at a later time in a coalesced manner.

Chaining

In addition to property changes, set() returns the value of the object itself so you can do chaining like this:

record.set('firstName', 'Charles').set('lastName', 'Jolley');
Parameters:
key String|Hash
the property to set
value Object
the value to set or null.
Returns:
SC.Observable
setIfChanged(key, value)

Sets the property only if the passed value is different from the current value. Depending on how expensive a get() is on this property, this may be more efficient.

NOTE: By default, the set() method will not set the value unless it has changed. However, this check can skipped by setting .property().idempotent(NO) setIfChanged() may be useful in this case.

Parameters:
key String|Hash
the key to change
value Object
the value to change
Returns:
SC.Observable
setPath(path, value)
Navigates the property path, finally setting the value.
Parameters:
path String
the property path to set
value Object
the value to set
Returns:
SC.Observable
setPathIfChanged(path, value)

Navigates the property path, finally setting the value but only if the value does not match the current value. This will avoid sending unnecessary change notifications.

Parameters:
path String
the property path to set
value Object
the value to set
Returns:
Object
this
toggleProperty(key, value, alt)
Inverts a property. Property should be a bool.
Parameters:
key String
property name
value Object
optional parameter for "true" value
alt Object
optional parameter for "false" value
Returns:
Object
new value
unknownProperty(key, value)

Called whenever you try to get or set an undefined property.

This is a generic property handler. If you define it, it will be called when the named property is not yet set in the object. The default does nothing.

Parameters:
key String
the key that was requested
value Object
The value if called as a setter, undefined if called as a getter.
Returns:
Object
The new value for key.
Documentation generated by JsDoc Toolkit 2.4.0 on Fri Nov 28 2014 17:58:15 GMT+0100 (CET)