4 ms·
I've used bind to do partial function application for quite a while, and it really is a convenient pattern to use. It does have the downside that it's a bit har
by timothya 13y ago
I've used bind to do partial function application for quite a while, and it really is a convenient pattern to use. It does have the downside that it's a bit harder to quickly understand what's going on, though, since the arguments being passed into a function can come from different places.
My common use case is when I'm setting up event handlers and I want the event handler to know about a companion object I have to the element in the DOM. For example:
MyObject.prototype.buildDom_ = function() {
for (var i = 0; i < buttons.length; i++) {
var button = new MyButton(...);
this.myButtons_.push(button);
var element = document.createElement('div');
element.addEventListener('click', this.handleClick_.bind(this, button));
this.rootElement_.appendChild(element);
}
};
MyObject.prototype.handleClick_ = function(button, clickEvent) {
// I have access to the MyButton instance passed in.
};
In this case, I use the partial application to pass in the MyButton instance so that when I'm in the handler for a button click, I have access to the original JavaScript object that was created when the event handler was set up.