Underscore Extension: Observer Pattern

Introduction

I thought this would be a handy snippet for anyone who wants to enable event handling on any arbitrary object. I decided to augment Underscore.js because these methods should to be on every Javascripter’s “Utility Belt”. I decided to use Node-like methods – on, once, emit, & removeEvent.

Code

_.mixin({
on : function(obj, event, callback) {
// Define a global Observer
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
if(this.isUndefined(obj._events)) obj._events = {};
if (!(event in obj._events)) obj._events[event] = [];
obj._events[event].push(callback);
return this;
},
once : function(obj, event, callback) {
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
var removeEvent = function() { _.removeEvent(obj, event); };
callback = _.compose(removeEvent, callback);
this.on(obj, event, callback);
},
emit : function(obj, event, args){
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
if(this.isUndefined(obj._events)) return;
if (event in obj._events) {
var events = obj._events[event].concat();
for (var i = 0, ii = events.length; i < ii; i++)
events[i].apply(obj, args === undefined ? [] : args);
}
return this;
},
removeEvent : function(obj, event) {
if(this.isString(obj)) { event = obj; obj = this; }
if(this.isUndefined(obj._events)) return;
console.log("remove");
delete obj._events[event];
}
});

Usage

Example 1: Listen for events on an arbitrary object

Car = {
color : 'blue',
seats : 4
};
_(Car).on('ready', function(sound) {
alert(sound + "!");
})
_(Car).emit('ready', ['honk']);

Example 2: Define global events

_.on('ready', function(sound) {
alert(sound + "!");
})
_.emit('ready', ['phew']);
_.removeEvent('ready');
_.emit('ready', ['come again?']); // Will not fire!

Example 3: Listening for an event “once”

_.once('ready', function(sound) {
alert(sound + "!");
})
_.emit('ready', ['phew']);
_.emit('ready', ['come again?']); // Will not fire!

Conclusion

And that’s my quick little snippet for you this morning. Let me know if you have any questions!

Comments

Monday, February 14th, 2011

[...] This post was mentioned on Twitter by 文殊堂, wjsnews. wjsnews said: Underscore Extension: Observer Pattern https://bit.ly/hJaoOO [...]

We highly recommend you our friends Cpasbien to download any films, movies, songs, books or files you need.