1

In my view class initialize function, _.bind(this.appendSection, this) does not work, but _.bindAll(this, 'appendSection') works. I am very confused...

Here is the code:

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);
        },
    });  
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
Rn2dy
  • 4,112
  • 12
  • 43
  • 59

1 Answers1

6

From the fine manual:

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

Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. [...]

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

Unfortunately the manual isn't quite so fine and you have to see what's implied by the example code:

func = _.bind(func, ...);

_.bind returns the bound function, it doesn't modify it in-place. You'd have to say this:

this.appendSection = _.bind(this.appendSection, this);

if you wanted to use _.bind. _.bindAll on the other hand, binds methods in place. There is more discussion on these methods over here.

Community
  • 1
  • 1
mu is too short
  • 426,620
  • 70
  • 833
  • 800