Skip to content

Instantly share code, notes, and snippets.

@millermedeiros
Created March 15, 2011 15:18
Show Gist options
  • Save millermedeiros/870867 to your computer and use it in GitHub Desktop.
Save millermedeiros/870867 to your computer and use it in GitHub Desktop.
JavaScript Chaining Example
//
// Orthodox Chaining
//
//basic Object that implements chaining
var myObj = {
_val : 'lorem',
val : function(val){
if(val === void(0)){
return this._val;
}else{
this._val = val;
return this; //chain
}
},
foo : function(){
console.log(this.val());
return this; //chain
}
};
//"chain, chain, chain..."
myObj.foo().val('ipsum').foo();
//
// Chainer.js
//
// Chain Helpers ------------
//===========================
/*!
* Helper for creating chainable functions/getters/setters
* @author Miller Medeiros (http://millermedeiros.com)
* @version 0.2 (2011/03/16)
* Released under the WTFPL (http://sam.zoy.org/wtfpl/)
*/
var chainer = {
method : function(fnName, scope, chain){
return function(){
return scope[fnName].apply(scope, arguments) || chain;
};
},
property : function(propName, scope, chain){
return function(val){
if(typeof val === 'undefined'){
return scope[propName];
}else{
scope[propName] = val;
return chain;
}
};
},
create : function(target){
var prop, obj = {};
for(prop in target){
//no need to filter properties of the prototype, let js-lint complain...
obj[prop] = (typeof target[prop] === 'function')? this.method(prop, target, obj) : this.property(prop, target, obj);
}
return obj;
}
};
// Example ------------------
//===========================
//base object
var base = {
val : 'lorem',
foo : function(){
console.log(this.val);
}
};
//create a new object that wrap calls to the "base" object
var myObj2 = chainer.create(base);
//"chain, chain, chain.."
myObj2.foo().val('ipsum').foo();
@millermedeiros
Copy link
Author

I've been delaying for a long time to create a project page for this code and rename it as trainwreck, not sure if I ever will..

@millermedeiros
Copy link
Author

finely spent some time writing a readme file and released it last night as trainwreck.js...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment