Skip to content

Instantly share code, notes, and snippets.

@kuzmicheff
Created September 16, 2017 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuzmicheff/6a69c16d758691b15bf1c2d614f6885b to your computer and use it in GitHub Desktop.
Save kuzmicheff/6a69c16d758691b15bf1c2d614f6885b to your computer and use it in GitHub Desktop.
Observer pattern implementation in JavaScript
function Click() {
this.handlers = []; // observers
}
Click.prototype = {
subscribe: function(fn) {
this.handlers.push(fn);
},
unsubscribe: function(fn) {
this.handlers = this.handlers.filter(
function(item) {
if (item !== fn) {
return item;
}
}
);
},
fire: function(o, thisObj) {
var scope = thisObj || window;
this.handlers.forEach(function(item) {
item.call(scope, o);
});
}
}
// log helper
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { alert(log); log = ""; }
}
})();
function run() {
var clickHandler = function(item) {
log.add("fired: " + item);
};
var click = new Click();
click.subscribe(clickHandler);
click.fire('event #1');
click.unsubscribe(clickHandler);
click.fire('event #2');
click.subscribe(clickHandler);
click.fire('event #3');
log.show();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment