骨干_.bind无法正常工作

Rn2*_*2dy 1 backbone.js underscore.js

在我的视图类初始化函数,_.bind(this.appendSection, this)不起作用,但_.bindAll(this, 'appendSection')工作.我很迷茫...

这是代码:

TemplateBuilder.Views.TemplateView = Backbone.View.extend({
        el: $('div#evalTemplate'),

        initialize: function(){
            this.collection.on('reset', this.render, this);
            //_.bind(this.appendSection, this);
            _.bindAll(this, 'appendSection');                
        },

        events: {
            'click button#addSection': 'addSection'
        },

        render: function(){
            this.collection.each(this.appendSection);
            return this;
        },

        appendSection: function(section){                
            var view = new TemplateBuilder.Views.InstructionView({model: section});
            this.$el.append(view.render().el);
        },

        addSection: function(){
            var newSection = new TemplateBuilder.Models.Section();                
            this.collection.add(newSection);
            this.appendSection(newSection);
        },
    });  
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 6

精细手册:

捆绑 _.bind(function, object, [*arguments])

结合的功能的对象,这意味着每当调用该函数时,的值将是对象.[...]

var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name : 'moe'}, 'hi');
func();
=> 'hi: moe'
Run Code Online (Sandbox Code Playgroud)

不幸的是,手册不是那么精细,你必须看看示例代码隐含的内容:

func = _.bind(func, ...);
Run Code Online (Sandbox Code Playgroud)

_.bind返回绑定函数,它不会就地修改它.你不得不这样说:

this.appendSection = _.bind(this.appendSection, this);
Run Code Online (Sandbox Code Playgroud)

如果你想使用_.bind._.bindAll另一方面,将方法绑定到位.有这些方法的详细讨论在这里.