mikemaccana
mikemaccana

Reputation: 123188

How can I convert this working native ES5 code to use underscore's _.bind() instead?

I have an existing project that (sadly) uses underscore.js, rather than an ES5 shim, to support IE8 and other non-ES5 browsers. I'm used to ES5, but don't generally use underscore. I have read the underscore documentation on _.bind and attempted to get it to work.

Here is a working example using native ES5:

// Greets people
HelloThing = function (greeting) {
    this.greeting = greeting;

    this.waitAndSayHello = function() {
        setTimeout(function() { 
            console.log(this.greeting)
        }.bind(this), 500);
    }
}


var pretend_thing = new HelloThing('hello world');
pretend_thing.waitAndSayHello();

Here is a failing attempt using underscore from my understanding of the documentation:

// Greets people
HelloThing = function (greeting) {
    this.greeting = greeting;

    this.waitAndSayHello = function() {
        var greet = function() { 
            alert(this.greeting)
        }
        _.bind(greet, this)
        setTimeout(greet, 500);
    }
}


var pretend_thing = new HelloThing('hello world');
pretend_thing.waitAndSayHello();​

How can I make underscore work?

Upvotes: 2

Views: 84

Answers (1)

James Allardice
James Allardice

Reputation: 165971

The _.bind() method returns a bound function. You don't do anything with that returned function. Assign it to something and use that reference instead of the original greet reference:

var greet = function() { 
    alert(this.greeting)
};
greet = _.bind(greet, this);
setTimeout(greet, 500);

If you expand your ES5 example, you will see that this is effectively what is happening with the native bind method - you can just call directly on a function object since it's a property of Function.prototype:

var greet = function() {
    alert(this.greeting);
};
greet = greet.bind(this);
setTimeout(greet, 500);

Upvotes: 2

Related Questions