Repository navigation
Cu.ObservableCollection
ObservableCollection wraps an array object. It's important to note that it does not derive from Array itself. You can access the array directly by using the val function as you would with a regular Observable. To add or remove value from the list, simply call the add or remove function.
var names = new Cu.ObservableCollection(['Chris', 'Joe', 'Mike']);
names.add('Terry'); // Adds to the end.
names.remove('Joe'); // Removes the first occurrence.
// names.val() is now ['Chris', 'Mike', 'Terry']It's also possible to add and remove at an index, simply by adding an index parameter to add or calling removeAt.
var names = new Cu.ObservableCollection(['Chris', 'Joe', 'Mike']);
names.add('Terry', 1); // Adds after first item.
names.removeAt(2); // Removes the item with index 2 (the third item).
// names.val() is now ['Chris', 'Terry', 'Mike']Event subscription with ObservableCollection works a bit differently, because it exposes multiple events. When you subscribe to a change event, you need to specify on the spot which one you're subscribing to.
var names = new Cu.ObservableCollection(['Chris', 'Joe', 'Mike']);
names.subscribe('itemAdded', function(newVal, atIndex) {
console.log(newVal + ' was added at ' + atIndex);
});
names.subscribe('itemRemoved', function(removedVal, atIndex) {
console.log(removedVal + ' was removed from ' + atIndex);
});
names.subscribe('collectionReplaced', function(newVal) {
console.log('Array was replaced with a new one of length ' + newVal.length);
});If you need to subscribe to multiple events, ObservableCollection also provides a convenience method for bulk subscription, because it extends copper's EventHost.
var names = new Cu.ObservableCollection(['Chris', 'Joe', 'Mike']);
names.subscribe({
itemAdded: function(newVal, atIndex) {
console.log(newVal + ' was added at ' + atIndex);
},
itemRemoved: function(removedVal, atIndex) {
console.log(removedVal + ' was removed from ' + atIndex);
},
collectionReplaced: function(newVal) {
console.log('Array was replaced with a new one of length ' + newVal.length);
}
});