iSofia
iSofia

Reputation: 1532

KnockoutJS: Function Scope Error

This code is in a KnockoutJS viewmodel:

function myViewModel()
{
    this.prop1 = ko.observable(123);
    this.prop2 = ko.observable("Hello");
    ..
    ..
}

myViewModel.prototype.func1 = function()
    {
  alert(this.prop1());             //works fine here

        myTimer = setTimeout(function()
        {
            alert(this.prop1());   //this.prop1() raises an undefined error
        }, 3000);                  //from console: Uncaught TypeError: undefined is not a function  
};

Why is the property not recognized within the timer callback? Looks like a scope issue, but I can't seem to solve it.

Upvotes: 0

Views: 67

Answers (1)

Jeroen
Jeroen

Reputation: 63830

You should read about Javascript scopes and the var self = this idiom. The this keyword can behave unexpectedly in callback functions, as it may be set to something unexpected (like the function calling the timeout callback, or window, or...).

Something like* this will be an immediate solution to your problem:

myViewModel.prototype.func1 = function()
{
    var self = this;
    alert(self.prop1());             //works fine here

    myTimer = setTimeout(function() {
        alert(self.prop1());
    }, 3000);                
};

* "like" this, because your question does not have code to actually reproduce your problem; a repro would be much more useful in helping you solve a problem

Upvotes: 2

Related Questions