/ Published in: JavaScript
URL: http://www.dustindiaz.com/basement/javascript-observer-class.html
Expand |
Embed | Plain Text
<!DOCTYPE HTML> <html lang="en"> <head> <title></title> <script> function Observer() { this.fns = []; } Observer.prototype = { subscribe: function(fn) { this.fns.push(fn); }, unsubscribe: function(fn) { this.fns = this.fns.filter( function(el) { if ( el !== fn ) { return el; } } ); }, fire: function(o, thisObj) { var scope = thisObj || window; this.fns.forEach( function(el) { el.call(scope, o); } ); } }; var o = new Observer; o.fire('here is my data'); var fn = function fn() { console.log('data data'); }; var fn3 = function fn3() { console.log('data data3 '); }; o.subscribe(fn); o.subscribe(fn3); o.unsubscribe(fn); o.fire('here is my data'); </script> </head> <body></body> </html>
You need to login to post a comment.
