Skip to content

Instantly share code, notes, and snippets.

@yeco
Created August 16, 2012 19:37
Show Gist options
  • Select an option

  • Save yeco/3372959 to your computer and use it in GitHub Desktop.

Select an option

Save yeco/3372959 to your computer and use it in GitHub Desktop.
Simple event emmitter / observable
function Observable() {
this.listeners = [];
}
Observable.prototype = {
constructor: Observable,
observe: function( fn ) {
this.listeners.push( fn );
},
unobserve: function( fn ) {
var index;
index = this.listeners.indexOf( fn );
if( index > -1 ) {
this.listeners.splice( index, 1 );
}
},
update: function() {
var listeners = this.listeners,
len = listeners.length,
i;
for( i = 0; i < len; ++i ) {
listeners[i].apply( null, arguments );
}
}
};
//Usage
function App() {
this.someEventHappened = new Observable;
this.someOtherEventHappened = new Observable;
}
var myApp = new App();
myApp.someEventHappened.observe( function() {
console.log( "someEvent" );
});
myApp.someEventHappened.update(); //Should normally happen inside of the object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment