Repository navigation
Cu.EventHost
cammerman edited this page Jan 11, 2012
·
1 revision
When you create a new EventHost you pass in a set of event names. The EventHost will define events with these names, and offer subscription tracking and callback for these events.
var events = new Cu.EventHost(['itemAdded', 'itemRemoved', 'collectionReplaced']);
// events now offers the same events as an ObservableCollection.
var handler = function (newVal, atIndex) {
console.log(newVal + ' was added at ' + atIndex);
};
event.subscribe('itemAdded', handler);
// Now listening.
event.raise('itemAdded', 'x', 1);
// Log: 'x was added at 1'
event.unsubscribe('itemAdded', handler);
// No longer listening.With an EventHost you can bulk subscribe to multiple events at the same time using object notation, as in the ObservableCollection above (repeated here).
var events = new Cu.EventHost(['itemAdded', 'itemRemoved', 'collectionReplaced']);
events.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);
}
});Raising events on an EventHost works similarly to subscribing, but without support for bulk operations.
var events = new Cu.EventHost(['something happened']);
events.subscribe('something happened', function() {
console.log('Something amazing has happened!');
});
events.raise('something happened');Finally, you can unsubscribe all subscriptions on an EventHost without hanging onto references to all the registered functions, by making a single, simple function call.
var events = new Cu.EventHost(['one', 'two', 'three']);
events.subscribe({
one: function () { console.log('one!'); },
two: function () { console.log('two!'); },
three: function () { console.log('three!'); }
});
events.raise('one');
// Logged 'one!'l
events.release();
events.raise('one');
// Nothing happened.