Skip to content

Instantly share code, notes, and snippets.

@voidfiles
Created February 11, 2010 18:24
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 voidfiles/301782 to your computer and use it in GitHub Desktop.
Save voidfiles/301782 to your computer and use it in GitHub Desktop.
function Subscriber(){
this.events = {};
}
Subscriber.prototype.create = function(event){
if(this.events[event]){
return;
}
this.events[event] = [];
return;
};
Subscriber.prototype.subscribe = function( event, callback, scope){
if(!this.events[event]){ return; }
this.events[event].push({callback:callback,scope:scope});
};
Subscriber.prototype.trigger = function(event,data){
if(!this.events[event]) { return; }
var i,
callback,
scope,
output;
for( i in this.events[event]){
callback = this.events[event][i]["callback"];
scope = this.events[event][i]["scope"];
if(!scope){
output = callback(data);
} else {
output = callback.apply(scope, [data]);
}
}
return;
};
mySubscriber = new Subscriber();
myCallback = function(){
console.log("Test 1");
};
mySubscriber.create("testing");
mySubscriber.subscribe("testing", myCallback);
mySubscriber.trigger("testing");
mySecondCallback = function(){
console.log(this.message);
};
scope = {
message: "Test 2"
};
mySubscriber.create("testing2");
mySubscriber.subscribe("testing2", mySecondCallback,scope);
mySubscriber.trigger("testing2");
myThirdCallback = function(data){
console.log("scope",this.message, "data",data.message);
};
scope = {
message: "Test 3"
};
data = {
message: "Test 3 data"
};
mySubscriber.create("testing3");
mySubscriber.subscribe("testing3", myThirdCallback,scope);
mySubscriber.trigger("testing3", data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment