Skip to content

Instantly share code, notes, and snippets.

@skeate
Last active August 29, 2015 14:23
Show Gist options
  • Save skeate/2917e5d13a7b98282af9 to your computer and use it in GitHub Desktop.
Save skeate/2917e5d13a7b98282af9 to your computer and use it in GitHub Desktop.
Javascript chainable if
Object.prototype.if = function(cond) {
var self = this;
var wrapFunc = function(f) {
return function() {
if (cond) {
return f.apply(self, arguments);
} else {
return self;
}
};
};
for (var prop in this) {
if (typeof(this[prop]) === 'function') {
this[prop] = wrapFunc(this[prop]);
}
}
return this;
};
// example
$('body')
.if(true)
.css('background', 'blue')
.if(false)
.css('background', 'green')
// result: body background is blue
@dbazile
Copy link

dbazile commented Jun 24, 2015

ಠ_ಠ

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