Skip to content

Instantly share code, notes, and snippets.

@mark-rushakoff
Created December 23, 2011 19:36
Show Gist options
  • Save mark-rushakoff/1515168 to your computer and use it in GitHub Desktop.
Save mark-rushakoff/1515168 to your computer and use it in GitHub Desktop.
Underscore mixins for function binding helpers
// 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