1

I have the following class. It has a bug since this reference at this.handlers (line 2) is different from this in this.setTimeRange (line 4)

function Synchronized() {
    this.handlers = [];
    $("#masterSlider").rangeSlider();

    $("#masterSlider").bind("valuesChanging", function(e, data) {
        this.setTimeRange(data.values.min, data.values.max);
    });

}

Synchronized.prototype = {
    setTimeRange: function(lowerBound, upperBound) {
        console.log(lowerBound, upperBound);
        this.lowerBound = lowerBound;
        this.upperBound = upperBound;
        $("#masterSlider").rangeSlider("bounds", this.lowerBound, this.upperBound);
    },
}

How could I call class method from a callback function?

Dzung Nguyen
  • 3,794
  • 9
  • 48
  • 86

2 Answers2

2

You have several options. The three most common ones:

Create a variable to store a copy of this that you can close over

var that = this;
$("#masterSlider").bind("valuesChanging", function(e, data) {
    that.setTimeRange(data.values.min, data.values.max);
});

Use function.prototype.bind on your anonymous function to return another function which has a specified value of this:

$("#masterSlider").bind("valuesChanging", (function(e, data) {
    this.setTimeRange(data.values.min, data.values.max);
}).bind(this));

Use an ES6 arrow function instead of an anonymous function:

$("#masterSlider").bind("valuesChanging", (e, data) => this.setTimeRange(data.values.min, data.values.max));
PMV
  • 2,058
  • 1
  • 10
  • 15
1

you should save the function reference before you enter to the callback and loose the reference. so one solution is like this :

   var self = this;
   $("#masterSlider").bind("valuesChanging", function(e, data) {
  self.setTimeRange(data.values.min, data.values.max);
 });