Class: SC.Binding

A binding simply connects the properties of two objects so that whenever the value of one property changes, the other property will be changed also. You do not usually work with Binding objects directly but instead describe bindings in your class definition using something like:

valueBinding: "MyApp.someController.title"

This will create a binding from "MyApp.someController.title" to the "value" property of your object instance automatically. Now the two values will be kept in sync.

Customizing Your Bindings

In addition to synchronizing values, bindings can also perform some basic transforms on values. These transforms can help to make sure the data fed into one object always meets the expectations of that object regardless of what the other object outputs.

To customize a binding, you can use one of the many helper methods defined on SC.Binding like so:

valueBinding: SC.Binding.single("MyApp.someController.title")

This will create a binding just like the example above, except that now the binding will convert the value of MyApp.someController.title to a single object (removing any arrays) before applying it to the "value" property of your object.

You can also chain helper methods to build custom bindings like so:

valueBinding: SC.Binding.single("MyApp.someController.title").notEmpty(null,"(EMPTY)")

This will force the value of MyApp.someController.title to be a single value and then check to see if the value is "empty" (null, undefined, empty array, or an empty string). If it is empty, the value will be set to the string "(EMPTY)".

One Way Bindings

One especially useful binding customization you can use is the oneWay() helper. This helper tells SproutCore that you are only interested in receiving changes on the object you are binding from. For example, if you are binding to a preference and you want to be notified if the preference has changed, but your object will not be changing the preference itself, you could do:

bigTitlesBinding: SC.Binding.oneWay("MyApp.preferencesController.bigTitles")

This way if the value of MyApp.preferencesController.bigTitles changes the "bigTitles" property of your object will change also. However, if you change the value of your "bigTitles" property, it will not update the preferencesController.

One way bindings are almost twice as fast to setup and twice as fast to execute because the binding only has to worry about changes to one side.

You should consider using one way bindings anytime you have an object that may be created frequently and you do not intend to change a property; only to monitor it for changes. (such as in the example above).

Adding Custom Transforms

In addition to using the standard helpers provided by SproutCore, you can also defined your own custom transform functions which will be used to convert the value. To do this, just define your transform function and add it to the binding with the transform() helper. The following example will not allow Integers less than ten. Note that it checks the value of the bindings and allows all other values to pass:

valueBinding: SC.Binding.transform(function (value, binding) {
    return ((SC.typeOf(value) === SC.T_NUMBER) && (value < 10)) ? 10 : value;
  }).from("MyApp.someController.value")

If you would like to instead use this transform on a number of bindings, you can also optionally add your own helper method to SC.Binding. This method should simply return the value of this.transform(). The example below adds a new helper called notLessThan() which will limit the value to be not less than the passed minimum:

SC.Binding.notLessThan = function (minValue) {
  return this.transform(function (value, binding) {
    return ((SC.typeOf(value) === SC.T_NUMBER) && (value < minValue)) ? minValue : value;
  });
};

You could specify this in your core.js file, for example. Then anywhere in your application you can use it to define bindings like so:

valueBinding: SC.Binding.from("MyApp.someController.value").notLessThan(10)

Also, remember that helpers are chained so you can use your helper along with any other helpers. The example below will create a one way binding that does not allow empty values or values less than 10:

valueBinding: SC.Binding.oneWay("MyApp.someController.value").notEmpty().notLessThan(10)

Note that the built in helper methods all allow you to pass a "from" property path so you don't have to use the from() helper to set the path. You can do the same thing with your own helper methods if you like, but it is not required.

Creating Custom Binding Templates

Another way you can customize bindings is to create a binding template. A template is simply a binding that is already partially or completely configured. You can specify this template anywhere in your app and then use it instead of designating your own custom bindings. This is a bit faster on app startup but it is mostly useful in making your code less verbose.

For example, let's say you will be frequently creating one way, not empty bindings that allow values greater than 10 throughout your app. You could create a binding template in your core.js like this:

MyApp.LimitBinding = SC.Binding.oneWay().notEmpty().notLessThan(10);

Then anywhere you want to use this binding, just refer to the template like so:

valueBinding: MyApp.LimitBinding.beget("MyApp.someController.value")

Note that when you use binding templates, it is very important that you always start by using beget() to extend the template. If you do not do this, you will end up using the same binding instance throughout your app which will lead to erratic behavior.

How to Manually Activate a Binding

All of the examples above show you how to configure a custom binding, but the result of these customizations will be a binding template, not a fully active binding. The binding will actually become active only when you instantiate the object the binding belongs to. It is useful however, to understand what actually happens when the binding is activated.

For a binding to function it must have at least a "from" property and a "to" property. The from property path points to the object/key that you want to bind from while the to path points to the object/key you want to bind to.

When you define a custom binding, you are usually describing the property you want to bind from (such as "MyApp.someController.value" in the examples above). When your object is created, it will automatically assign the value you want to bind "to" based on the name of your binding key. In the examples above, during init, SproutCore objects will effectively call something like this on your binding:

binding = this.valueBinding.beget().to("value", this);

This creates a new binding instance based on the template you provide, and sets the to path to the "value" property of the new object. Now that the binding is fully configured with a "from" and a "to", it simply needs to be connected to become active. This is done through the connect() method:

binding.connect();

Now that the binding is connected, it will observe both the from and to side and relay changes.

If you ever needed to do so (you almost never will, but it is useful to understand this anyway), you could manually create an active binding by doing the following:

SC.Binding.from("MyApp.someController.value")
   .to("MyApp.anotherObject.value")
   .connect();

You could also use the bind() helper method provided by SC.Object. (This is the same method used by SC.Object.init() to setup your bindings):

MyApp.anotherObject.bind("value", "MyApp.someController.value");

Both of these code fragments have the same effect as doing the most friendly form of binding creation like so:

MyApp.anotherObject = SC.Object.create({
    valueBinding: "MyApp.someController.value",

    // OTHER CODE FOR THIS OBJECT...

  });

SproutCore's built in binding creation method make it easy to automatically create bindings for you. You should always use the highest-level APIs available, even if you understand how to it works underneath.

Defined in: binding.js

Since:
SproutCore 1.0

Field Summary

Class Methods

Instance Methods

Field Detail

SC.Binding.isBinding

Extend SC.Binding with properites that make it easier to detect bindings in the inspector


Defined in: binding.js.
isDestroyed Boolean
Indicates when the binding has been destroyed.
Default value:
NO

Class Method Detail

dateTime(format)

Adds a transform to format the DateTime value to a String value according to the passed format string.

valueBinding: SC.Binding.dateTime('%Y-%m-%d %H:%M:%S')
                        .from('MyApp.myController.myDateTime');

Defined in: datetime.js.
Parameters:
format String
format string
Returns:
SC.Binding
this
displayValue()

Defined in: binding.js.
encodeDesign(coder)

Defined in: binding.js.
Parameters:
coder

Instance Method Detail

and(pathA, pathB)

Adds a transform that forwards the logical 'AND' of values at 'pathA' and 'pathB' whenever either source changes. Note that the transform acts strictly as a one-way binding, working only in the direction

'pathA' AND 'pathB' --> value (value returned is the result of ('pathA' && 'pathB'))

Usage example where a delete button's 'isEnabled' value is determined by whether something is selected in a list and whether the current user is allowed to delete:

deleteButton: SC.ButtonView.design({ isEnabledBinding: SC.Binding.and('MyApp.itemsController.hasSelection', 'MyApp.userController.canDelete') })

Parameters:
pathA String
The first part of the conditional
pathB String
The second part of the conditional
applyBindingValue()

This method is called at the end of the Run Loop to relay the changed binding value from one side to the other.

beget(fromPath)

This is the core method you use to create a new binding instance. The binding instance will have the receiver instance as its parent which means any configuration you have there will be inherited.

The returned instance will also have its parentBinding property set to the receiver.

Parameters:
fromPath String Optional
Returns:
SC.Binding
new binding instance
bool(fromPath)

Adds a transform to convert the value to a bool value. If the value is an array it will return YES if array is not empty. If the value is a string it will return YES if the string is not empty.

Parameters:
fromPath String Optional
Returns:
SC.Binding
this
builder()
Returns a builder function for compatibility.
connect()

Attempts to connect this binding instance so that it can receive and relay changes. This method will raise an exception if you have not set the from/to properties yet.

Returns:
SC.Binding
this
disconnect()

Disconnects the binding instance. Changes will no longer be relayed. You will not usually need to call this method.

Returns:
SC.Binding
this
flushPendingChanges()
Call this method on SC.Binding to flush all bindings with changed pending.
Returns:
Boolean
YES if changes were flushed.
from(propertyPath, root)

This will set "from" property path to the specified value. It will not attempt to resolve this property path to an actual object/property tuple until you connect the binding.

The binding will search for the property path starting at the root level unless you specify an alternate root object as the second parameter to this method. Alternatively, you can begin your property path with either "." or "*", which will use the root object of the to side be default. This special behavior is used to support the high-level API provided by SC.Object.

Parameters:
propertyPath String|Tuple
A property path or tuple
root Object Optional
root object to use when resolving the path.
Returns:
SC.Binding
this
fromPropertyDidChange(target, key)

Invoked whenever the value of the "from" property changes. This will mark the binding as dirty if the value has changed.

Parameters:
target Object
The object that contains the key
key String
The name of the property which changed
isNull(fromPath)
Adds a transform that will return YES if the value is null or undefined, NO otherwise.
Parameters:
fromPath String Optional
Returns:
SC.Binding
this
multiple(fromPath)

Adds a transform that will convert the passed value to an array. If the value is null or undefined, it will be converted to an empty array.

Parameters:
fromPath String Optional
Returns:
SC.Binding
this
noError(fromPath, aFlag)

Specifies that the binding should not return error objects. If the value of a binding is an Error object, it will be transformed to a null value instead.

Note that this is not a transform function since it will be called at the end of the transform chain.

Parameters:
fromPath String Optional
from path to connect.
aFlag Boolean Optional
Pass NO to allow error objects again.
Returns:
SC.Binding
this
not(fromPath)

Adds a transform to convert the value to the inverse of a bool value. This uses the same transform as bool() but inverts it.

Parameters:
fromPath String Optional
Returns:
SC.Binding
this
notEmpty(fromPath, placeholder)

Adds a transform that will return the placeholder value if the value is null, undefined, an empty array or an empty string. See also notNull().

Parameters:
fromPath String
from path or null
placeholder Object Optional
Returns:
SC.Binding
this
notNull(fromPath, placeholder)

Adds a transform that will return the placeholder value if the value is null or undefined. Otherwise it will pass through untouched. See also notEmpty().

Parameters:
fromPath String
from path or null
placeholder Object Optional
Returns:
SC.Binding
this
oneWay(fromPath, aFlag)

Configures the binding as one way. A one-way binding will relay changes on the "from" side to the "to" side, but not the other way around. This means that if you change the "to" side directly, the "from" side may have a different value.

Parameters:
fromPath String Optional
from path to connect.
aFlag Boolean Optional
Pass NO to set the binding back to two-way
Returns:
SC.Binding
this
or(pathA, pathB)

Adds a transform that forwards the 'OR' of values at 'pathA' and 'pathB' whenever either source changes. Note that the transform acts strictly as a one-way binding, working only in the direction

'pathA' AND 'pathB' --> value (value returned is the result of ('pathA' || 'pathB'))

Parameters:
pathA String
The first part of the conditional
pathB String
The second part of the conditional
resetTransforms()

Resets the transforms for the binding. After calling this method the binding will no longer transform values. You can then add new transforms as needed.

Returns:
SC.Binding
this
single(fromPath, placeholder)

Adds a transform to the chain that will allow only single values to pass. This will allow single values, nulls, and error values to pass through. If you pass an array, it will be mapped as so:

[] => null
  [a] => a
  [a,b,c] => Multiple Placeholder

You can pass in an optional multiple placeholder or it will use the default.

Note that this transform will only happen on forwarded valued. Reverse values are send unchanged.

Parameters:
fromPath String
from path or null
placeholder Object Optional
placeholder value.
Returns:
SC.Binding
this
sync()

Calling this method on a binding will cause it to check the value of the from side of the binding matches the current expected value of the binding. If not, it will relay the change as if the from side's value has just changed.

This method is useful when you are dynamically connecting bindings to a network of objects that may have already been initialized.

to(propertyPath, root)

This will set the "to" property path to the specified value. It will not attempt to reoslve this property path to an actual object/property tuple until you connect the binding.

Parameters:
propertyPath String|Tuple
A property path or tuple
root Object Optional
root object to use when resolving the path.
Returns:
SC.Binding
this
toPropertyDidChange(target, key)

Invoked whenever the value of the "to" property changes. This will mark the binding as dirty only if:

  • the binding is not one way
  • the value does not match the stored transformedBindingValue

if the value does not match the transformedBindingValue, then it will become the new bindingValue.

Parameters:
target Object
The object that contains the key
key String
The name of the property which changed
toString()
transform(transformFunc)

Adds the specified transform function to the array of transform functions.

The function you pass must have the following signature:

function (value) {};

It must return either the transformed value or an error object.

Transform functions are chained, so they are called in order. If you are extending a binding and want to reset the transforms, you can call resetTransform() first.

Parameters:
transformFunc Function
the transform function.
Returns:
SC.Binding
this
Documentation generated by JsDoc Toolkit 2.4.0 on Sun Oct 27 2013 19:58:51 GMT-0600 (CST)