Last active
August 29, 2015 14:23
-
-
Save skeate/2917e5d13a7b98282af9 to your computer and use it in GitHub Desktop.
Javascript chainable if
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ಠ_ಠ