Skip to content

Instantly share code, notes, and snippets.

@rrgarciach
Created June 16, 2016 19:55
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 rrgarciach/d5829e78fc307ac86cfad5a70c868742 to your computer and use it in GitHub Desktop.
Save rrgarciach/d5829e78fc307ac86cfad5a70c868742 to your computer and use it in GitHub Desktop.
An Observer pattern example in JavaScript
function ObserverList(){
this.observerList = [];
}
ObserverList.prototype.add = function( obj ){
return this.observerList.push( obj );
};
ObserverList.prototype.count = function(){
return this.observerList.length;
};
ObserverList.prototype.get = function( index ){
if( index > -1 && index < this.observerList.length ){
return this.observerList[ index ];
}
};
ObserverList.prototype.indexOf = function( obj, startIndex ){
var i = startIndex;
while( i < this.observerList.length ){
if( this.observerList[i] === obj ){
return i;
}
i++;
}
return -1;
};
ObserverList.prototype.removeAt = function( index ){
this.observerList.splice( index, 1 );
};
// cat.stalk (boolean);
function Cat(name) {
this.name = name;
this.update = function() {
alert(this.name + ' ATTACKS !!!');
}
}
var cat1 = new Cat('Misifus');
var cat2 = new Cat('Benito');
var cat3 = new Cat('Garfield');
var cat4 = new Cat('Top Cat');
function Lure() {
this.stalkers = new ObserverList();
this.isMoving = false;
}
Lure.prototype.move = function(){
this.isMoving = true;
this.notify();
}
Lure.prototype.addStalker = function( stalker ){
this.stalkers.add( stalker );
};
Lure.prototype.removeStalker = function( stalker ){
this.stalkers.removeAt( this.stalkers.indexOf( stalker, 0 ) );
};
Lure.prototype.notify = function(){
var stalkerCount = this.stalkers.count();
for(var i=0; i < stalkerCount; i++){
this.stalkers.get(i).update();
}
};
var lure = new Lure();
lure.addStalker(cat1);
lure.addStalker(cat2);
lure.addStalker(cat3);
lure.addStalker(cat4);
lure.move();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment