Created
December 23, 2011 19:36
-
-
Save mark-rushakoff/1515168 to your computer and use it in GitHub Desktop.
Underscore mixins for function binding helpers
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
// Run with jsFiddle at http://jsfiddle.net/MarkRushakoff/jQwGz/ | |
_.mixin({ | |
bindFiltered : function(object, filterFunc) { | |
var funcNames = _(object).chain().functions().filter(filterFunc).value(); | |
var args = [object].concat(funcNames); | |
return _.bindAll.apply(_, args); | |
}, | |
bindMatching : function(object, regex) { | |
return _.bindFiltered(object, function(name) { return name.match(regex); }); | |
} | |
}); | |
(function runTests() { | |
test("bindFiltered", function() { | |
var moe = { | |
name : 'Moe', | |
sayHi : function() { | |
return "Hi from " + this.name; | |
}, | |
greetEveryone : function() { | |
return "Greetings from " + this.name; | |
}, | |
sayGoodbye : function() { | |
return "Bye from " + this.name; | |
} | |
}; | |
var curly = { | |
name : "Curly" | |
}; | |
_.bindFiltered(moe, function(funcName) {return funcName.length > 7;}); | |
// Two functions should be adequate for test, but I wanted to make sure that | |
// `apply` was used correctly in the definition of bindFiltered. | |
curly.sayHi = moe.sayHi; | |
curly.greetEveryone = moe.greetEveryone; | |
curly.sayGoodbye = moe.sayGoodbye; | |
equals(curly.sayHi(), "Hi from Curly", "bindFiltered does not bind functions that do not pass the filter"); | |
equals(curly.greetEveryone(), "Greetings from Moe", "bindFiltered binds functions that pass the filter"); | |
equals(curly.sayGoodbye(), "Bye from Moe", "bindFiltered binds functions that pass the filter"); | |
}); | |
test("bindMatching", function() { | |
var moe = { | |
name : 'Moe', | |
sayHi : function() { | |
return "Hi from " + this.name; | |
}, | |
greetEveryone : function() { | |
return "Greetings from " + this.name; | |
}, | |
sayGoodbye : function() { | |
return "Bye from " + this.name; | |
} | |
}; | |
var curly = { | |
name : "Curly" | |
}; | |
_.bindMatching(moe, /^say/); | |
curly.sayHi = moe.sayHi; | |
curly.greetEveryone = moe.greetEveryone; | |
curly.sayGoodbye = moe.sayGoodbye; | |
equals(curly.sayHi(), "Hi from Moe", "bindMatching binds functions whose names match the regex"); | |
equals(curly.greetEveryone(), "Greetings from Curly", "bindMatching does not bind functions whose names do not match the regex"); | |
equals(curly.sayGoodbye(), "Bye from Moe", "bindMatching binds functions whose names match the regex"); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment