Created
August 16, 2012 19:37
-
-
Save yeco/3372959 to your computer and use it in GitHub Desktop.
Simple event emmitter / observable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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