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);
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With