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.

Field Summary

Instance Methods

Field Detail

isObservable
Walk like that ol' duck

Instance Method Detail

addObserver

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:
String key
the key to observer
Object target
the target object to invoke
String|Function method
the method to invoke.
Object context
optional context
Returns:
SC.Object self
addObservesHandler

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 captial character then the path is considered relative to the window object.

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

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:
String key
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

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:
String key
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

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

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

didChangeFor allows you to determine if a property has changed since the last time the method was called. You must pass a unique context as the first parameter (so didChangeFor can identify which method is calling it), followed by a list of keys that should be checked for changes.

For example, in your render method you might pass the following context: if (this.didChangeFor('render','height','width')) { // Only render if changed }

In your view's update method, you might instead pass 'update':

if (this.didChangeFor('update', 'height', 'width')) { // Only update height and width properties }

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:
String|Object context
a unique identifier
String propertyNames
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

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:
String key
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

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

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

Parameters:
String path
The property path you want to retrieve
hasObserverFor

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:
String key
key to check
Returns:
Boolean
incrementProperty
Increments the value of a property.
Parameters:
String key
property name
Number increment
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
Logs the named properties to the SC.Logger.
Parameters:
String... propertyNames
one or more property names
notifyPropertyChange

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:
String key
The property key that has just changed.
Object value
The new value of the key. May be null.
Returns:
SC.Observable
observersForKey

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:
String key
the key to evaluate
Returns:
Array array of Observer objects, describing the observer.
propertyDidChange

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:
String key
The property key that has just changed.
Object value
The new value of the key. May be null.
Boolean _keepCache
Private property
Returns:
SC.Observable
propertyWillChange

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:
String key
The property key that is about to change.
Returns:
SC.Observable
registerDependentKey

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:
String key
the dependent key
Array|String dependentKeys
one or more dependent keys
Returns:
Object this
removeObserver

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:
String key
the key to observer
Object target
the target object to invoke
String|Function method
the method to invoke.
Returns:
SC.Observable receiver
removeObservesHandler

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 captial character then the path is considered relative to the window object.

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

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:
String|Hash key
the property to set
Object value
the value to set or null.
Returns:
SC.Observable
setIfChanged

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:
String|Hash key
the key to change
Object value
the value to change
Returns:
SC.Observable
setPath
Navigates the property path, finally setting the value.
Parameters:
String path
the property path to set
Object value
the value to set
Returns:
SC.Observable
setPathIfChanged

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:
String path
the property path to set
Object value
the value to set
Returns:
Object this
toggleProperty
Inverts a property. Property should be a bool.
Parameters:
String key
property name
Object value
optional parameter for "true" value
Object alt
optional parameter for "false" value
Returns:
Object new value
unknownProperty

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:
String key
the key that was requested
Object value
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 Thu Apr 11 2013 16:14:36 GMT+0800 (CST)