-2
    <img src="http://www.aero-sa.com/images/ajax-loader.gif" data-bind="visible:loading" />
var model = function() {
    var self = this;
    this.loading =  ko.observable(true);
    setTimeout(function() {
        self.loading(false);
    }, 4000);
}
ko.applyBindings(new model());

i have few question on the above code. what is this keyword here? this denote what? when i write the code like then image is not getting hide....why this keyword is not working setTimeout.

var model = function() {
        //var self = this;
        this.loading =  ko.observable(true);
        setTimeout(function() {
            this.loading(false);
        }, 4000);
    }
    ko.applyBindings(new model());

please explain if possible.

Thomas
  • 31,089
  • 118
  • 335
  • 589
  • 2
    possible duplicate of [JavaScript "this" keyword](http://stackoverflow.com/questions/3127429/javascript-this-keyword) also http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this and http://stackoverflow.com/questions/3309516/when-to-use-self-in-javascript – nemesv Jul 12 '13 at 11:14
  • `console.log()` is your friend! – Niko Jul 12 '13 at 11:16
  • Why did you create a new question while I tried to answer to your question here: http://stackoverflow.com/questions/17590336/how-to-bind-list-of-images-using-knockout-in-page-with-loading-spinner#comment25602854_17590336 – mael Jul 12 '13 at 12:16

3 Answers3

1

The second this is not working because you changed the context where this is valid... The second this is only valid for properties inside the setTimeout function.

This would work:

var model = function() {
    var self = this;
    self.loading =  ko.observable(true);
    setTimeout(function() {
        self.loading(false);
    }, 4000);
}
ko.applyBindings(new model());
Milaan
  • 108
  • 1
  • 5
1

Inside the setTimeout the 'this' context is of Window object. Where as the this outsite of setTimeout is of Model class constructor. So you have to use:

var self = this;

and then inside setTimeout use self instead of this.

Bhalchandra K
  • 2,511
  • 3
  • 24
  • 38