Skip to content

Instantly share code, notes, and snippets.

@xiaojue
Created November 27, 2011 04:53
Show Gist options
  • Save xiaojue/1396984 to your computer and use it in GitHub Desktop.
Save xiaojue/1396984 to your computer and use it in GitHub Desktop.
nodejs custom events
var events=function(){
this.map={};
};
events.prototype={
emit:function(eventname,args){
if(this.map[eventname]){
this.map[eventname].forEach(function(fn){
fn.apply(this,args);
});
}
},
on:function(eventname,callback){
if(this.map[eventname]){
this.map[eventname].push(callback);
}else{
this.map[eventname]=[callback];
}
}
}
var test=function(){
events.call(this);
}
test.prototype=Object.create(events.prototype,{
run:{
value:function(n){
var i=0;
while(i<n){
i++;
console.log(i);
if(i===5) this.emit('five',[i]);
}
}
}
});
var myEventTest=new test();
myEventTest.on('five',function(i){
console.log('five fired on '+i);
});
myEventTest.run(8);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment