Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore bindAll, explicit method naming

I am using _.bindAll in lots of my Backbone.Views.

_.bindAll(this, 'render', 'addOne', 'addAll', 'someFunctionA', 'someFunctionB');

While refactoring this becomes quite tedious as I need to keep the views methods and the name listings in sync. Both ways this often leads to simple errors.

As there is a short version of bindAll, which would eliminate this need, I am wondering what drawbacks (performance, readability, flexibility, ..) do exist and do you consider them acceptable to gain a bit of a productivity boost.

_.bindAll(this);
like image 364
SunnyRed Avatar asked Feb 07 '12 11:02

SunnyRed


2 Answers

There is no practical performance penalty for using that form of bindAll. However, it will be a pain if you do not want a method bound to this for some reason.

However, you may find that you do not need to use bindAll as often as you think. All methods that are bound to event handlers (with the events hash) are automatically bound to this.

Also, when you are explicitly binding an event, you can pass the this binding in the third param. For example:

this.model.bind('change', this.render, this)

like image 139
maxl0rd Avatar answered Oct 16 '22 11:10

maxl0rd


I'v used _.bindAll(this) in backbone project for a while. After profiling the code I'v realized that calls to _.bindAll takes notable part of all the function calls.
Based on the results of the performance test http://jsperf.com/underscore-bindall-this-vs-bindall-this-params it seems that explicit method naming is more performant (especially for objects with a lot of functions)

like image 31
Johnner Avatar answered Oct 16 '22 11:10

Johnner