2

How to maintain a reference to an instance, when using the setTimeout callback? E.G:

In my ViewModel (using Knockout)

var MyVM = function () {
  this.myFunc = function () {
    setTimeout("this.myCallback()", 2000);
  };
  this.myCallback = function() { this.myObservable(true); }
}

This fails.

williamsandonz
  • 15,864
  • 23
  • 100
  • 186

1 Answers1

3

You can add a private field :

var MyVM = function () {
    var self = this;
    this.myFunc = function () {
        setTimeout(self.myCallback, 2000);
    };
    this.myCallback = function() { self.myObservable(true); }
}
var vm = new MyVM();

Have a look at the RP Niemeyer's answer.

I hope it helps.

Community
  • 1
  • 1
Damien
  • 8,889
  • 3
  • 32
  • 40