Skip to content

Instantly share code, notes, and snippets.

@erayarslan
Created May 9, 2016 14:07
Show Gist options
  • Save erayarslan/d876538a0228ecc597cb5c25f42871fd to your computer and use it in GitHub Desktop.
Save erayarslan/d876538a0228ecc597cb5c25f42871fd to your computer and use it in GitHub Desktop.
observer pattern for js
var Observable = function () {
this.observers = [];
};
Observable.prototype.register = function ($) {
if (this.observers.indexOf($) == -1) {
this.observers.push($);
}
};
Observable.prototype.unregister = function ($) {
var index = this.observers.indexOf($);
if (index != -1) {
this.observers.splice(index, 1);
}
};
Observable.prototype.unregister_all = function () {
this.observers.splice(0, this.observers.length);
};
Observable.prototype.catch = function () {
for (var i in this.observers) {
this.observers[i].emit.apply(this, arguments);
}
};
var Observer = function () {
};
Observer.prototype.emit = function () {
};
var Obzy = function () {
Observer.apply(this, arguments);
};
Obzy.prototype = Object.create(Observer.prototype);
Obzy.prototype.constructor = Obzy;
Obzy.prototype.emit = function () {
console.log("hi", this.name);
};
var Human = function (name) {
Observable.apply(this, arguments);
this.name = name;
};
Human.prototype = Object.create(Observable.prototype);
Human.prototype.constructor = Human;
var eray = new Human("Eray");
var new_obzy = new Obzy();
eray.register(new_obzy);
eray.catch();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment