101010
101010

Reputation: 15726

How do I bind the "this" in a function body in IE-8 Javascript?

I'm doing some cross browser testing. Initially, I was using the bind() keyword in ECMAScript 5. It's not available in IE8. As a work-around, I am using some code from Yehuda Katz. His site suggests using a utility function in lieu of bind() when bind doesn't exist -- It doesn't exist in IE 8.

http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

   var bind = function (func, thisValue) {
           return function () {
                   return func.apply(thisValue, arguments);
           }
   }

In trying to use it, I'm getting an exception where it says "func.apply". I'm not passing in a function, I'm passing in an object, so apply() isn't there. Fine. But now I'm stuck again and back to square 1. How do I bind the "this" variable to a function body?

Summary: How do I bind the "this" variable to a function body?

<snip>

    MyView.prototype.OnSlider_Change = function (event, ui) {
           this.viewModel.setVariableX(ui.value * 100.0);
    }

<snip>

    $("#Slider").slider({
                   slide: (this.OnSlider_Change).bind(this),
                   change: (this.OnSlider_Change).bind(this)
           });

has become

   $("#Slider").slider({
           slide: bind(this, this.OnSlider_Change),
           change: bind(this, this.OnSlider_Change)
   });

Upvotes: 2

Views: 2758

Answers (2)

Sam Greenhalgh
Sam Greenhalgh

Reputation: 6136

With jquery you can use the proxy method that implements what your bind method is doing.

$("#Slider").slider({
    slide: $.proxy(this.OnSlider_Change, this),
    change: $.proxy(this.OnSlider_Change, this)
});

Upvotes: 6

James M
James M

Reputation: 16718

You just got the argument order wrong for that shim:

       slide: bind(this.OnSlider_Change, this),
       change: bind(this.OnSlider_Change, this)

Upvotes: 2

Related Questions