最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Underscore bindAll, explicit method naming - Stack Overflow

programmeradmin4浏览0评论

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

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

While refactoring this bees 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);

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

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

While refactoring this bees 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);
Share Improve this question edited Feb 7, 2012 at 18:16 SunnyRed asked Feb 7, 2012 at 11:37 SunnyRedSunnyRed 3,5554 gold badges37 silver badges58 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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./underscore-bindall-this-vs-bindall-this-params it seems that explicit method naming is more performant (especially for objects with a lot of functions)

发布评论

评论列表(0)

  1. 暂无评论