Skip to content

Instantly share code, notes, and snippets.

@edjafarov
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save edjafarov/08d0d236008b34ea339d to your computer and use it in GitHub Desktop.

Select an option

Save edjafarov/08d0d236008b34ea339d to your computer and use it in GitHub Desktop.
common Actions
var Emitter = require('events').EventEmitter;
var Actions = {
create: function(actionName){
var sequence = [];
sequence.push([function(result){
this.emit(result);
}]);
Actions[actionName] = function(params){
params._emitted = false;
params.emit = function(result){
if(this._emitted) return;
Actions.emit(actionName, result);
}
params.actionName = actionName;
var res = sequence.reduce(function(dostuff, func){
func = [].slice.call(func).map(function(funcArg){
return funcArg.bind(params);
});
return dostuff.then.apply(dostuff, func);
}, Promise.resolve());
};
var self = {
then: function(){
sequence.splice(sequence.length-1,0,arguments);
return self;
}
};
return self;
},
doAction: function(actionName){
var arg = [].slice.call(arguments);
Actions[arg.shift()].apply(this, arg);
}
};
Actions.__proto__ = new Emitter();
//USAGE
Actions.create('test').then(function(){
console.log(1, this);
return "result";
}).then(function(result){
console.log(2, this);
return true;
}).then(function(){
console.log(3, this);
return "OK";
});
Actions.on('test', function(result){
console.log(result);
})
Actions.test({a:1, b:2});
/*
* 1 Object {a: 1, b: 2}
* 2 Object {a: 1, b: 2}
* 3 Object {a: 1, b: 2}
* OK
*/
Actions.doAction('test', {a:1, b:2});
/*
* 1 Object {a: 1, b: 2}
* 2 Object {a: 1, b: 2}
* 3 Object {a: 1, b: 2}
* OK
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment