Skip to content

Instantly share code, notes, and snippets.

@omeroot
Created October 26, 2015 15:26
Show Gist options
  • Select an option

  • Save omeroot/d48e53230d1ee78803d3 to your computer and use it in GitHub Desktop.

Select an option

Save omeroot/d48e53230d1ee78803d3 to your computer and use it in GitHub Desktop.
var EventEmitter = require('events').EventEmitter;
EventEmitter.prototype.emit = function(type){
console.log(type);//output : end
var handler = this._events[type];
/**
*output: function(r, callback){
callback(r);
}
*
*/
console.log(handler);
if(Array.isArray(handler)){
var args = Array.prototype.slice.call(arguments, 1);
var listeners = handler.slice();
for(var i = 0 ;i< listeners.length ; i++){
console.log(listeners[i]);
listeners[i].apply(this, args);
}
}else if(typeof handler === 'function'){
var args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
};
function Test(){
this.on('end',function(r, callback){
callback(r);
});
}
Test.prototype = Object.create(EventEmitter.prototype);
Test.prototype.constructor = Test;
Test.prototype.factorial = function(n, callback){
var self = this;
var res = this.fact(n);
setTimeout(function(){
self.emit('end',res,callback);
},50);
};
Test.prototype.fact = function(n){
if(n == 1)
return 1;
return n * this.fact(n - 1);
};
var t = new Test();
var res;
t.factorial(5, function(result){
res = result;
console.log(res);//output : 120
});
console.log("last",res);//output : undefined
module.exports = Test;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment