Repository navigation
Cu.Observable
copper.js offers an implementation of an observable value. An observable is a simple object that wraps some value, and offers a subscription point for change events that are raised when the value is replaced. The built-in conventions in copper.js will look for Observable properties on your view-model, and attempt to find elements in the HTML, or handlers on the view object, which can be auto-bound to these properties.
To include an Observable on your model, simply call the copper.Observable constructor as below.
var viewModel = {
name: new Cu.Observable('Chris'),
age: new Cu.Observable(29),
sex: new Cu.Observable('M')
};Accessing or changing an observable isn't quite as easy as changing a normal property, because it's not a simple object. But it's still straightforward. It follows the jQuery getter/setter function overload pattern.
var age = new Cu.Observable(29); // Initialize
console.log(age.val()); // Get
age.val(30); // SetWhen you give an Observable a new value, it will call any subscriber callbacks that you have registered. Subscribing to an Observable is done via the subscribe function.
var age = new Cu.Observable(29);
age.subscribe(function(newVal) {
console.log('Age was changed to ' + newVal);
});
age.val(30); // Callback will fire here.Observable can hold any type of object you want. But it will only raise an event when that value is replaced. If you need to listen for changes to properties on your object, you'll need to explicitly raise events yourself, or use nested Observables and subscribe to those.
You can also store arrays in an Observable, but the event will only fire when the whole array is replaced. If you need to know when items are added or removed, you can use an ObservableCollection.