Created
November 27, 2011 04:53
-
-
Save xiaojue/1396984 to your computer and use it in GitHub Desktop.
nodejs custom events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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