Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore bind vs jQuery.proxy vs Native bind

I have some context issues in callback. I googled and found few option:

  1. Native bind - not supported by old browsers
  2. JQuery proxy
  3. underscore bind

I'll definitely use native bind if I don't have to support old browsers. Is there any significant difference between these one should be aware of?

Could these be used as an alternate to call/apply?

like image 375
RuntimeException Avatar asked Sep 17 '13 11:09

RuntimeException


1 Answers

AFAIK, There is a slight difference between bind and proxy, which can matter a lot if you are using jQuery. Function.prototype.bind always returns a new function pointer. jQuery.proxy only returns a new function if a proxy of the same args has not already been created. Not that you would want to do it like this, but:

$(elm).on('click', doStuff.bind(thing)); //adds event handler
$(elm).off('click', doStuff.bind(thing)); //does not remove event handler as 2nd call of doStuff.bind(thing) always returns a new/different function

$(elm).on('click', $.proxy(doStuff, thing)); //adds handler
$(elm).off('click', $.proxy(doStuff, thing));//DOES remove handler, as a second call to $.proxy(doStuff, thing) is smart enough to know about similar use-cases

//Likewise, if you just passed 'thing.doStuff()' into the $.off() method, it would also work
like image 103
Graza Avatar answered Sep 18 '22 13:09

Graza