Skip to content

Instantly share code, notes, and snippets.

@asci
Created August 3, 2015 08:38
Show Gist options
  • Save asci/886ccb2ec4dea0c3561a to your computer and use it in GitHub Desktop.
Save asci/886ccb2ec4dea0c3561a to your computer and use it in GitHub Desktop.
chainer
function toChain(target) {
var queue = [];
var lastReturn;
Object.keys(target).forEach(function (prop) {
var original;
if (typeof target[prop] === 'function') {
original = target[prop];
target[prop] = function () {
var args = arguments;
queue.push(function () {
original.apply(target, args);
});
return target;
}
}
});
return function () {
queue.forEach(function (fn) {
lastReturn = fn();
});
return lastReturn;
};
}
var obj = {
test: '',
fun1: function (test) {
this.test += test;
},
fun2: function (test2) {
this.test += test2;
},
getTest: function () {
return this.test;
},
log: function (str) {
console.log('======================log======================');
console.log(str);
},
fun3: function (test3) {
this.test += test3;
}
};
var run = toChain(obj);
obj
.fun1('test1')
.fun2('test2')
.log('my log')
.fun3('fun3')
.getTest();
console.log(run());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment