Roman Bekkiev
Roman Bekkiev

Reputation: 3118

knockout.js: this in child object

JS:

function Child() {
    this.method = function() {
         console.dir(this); // this should be 'p.child' <Child> since 
         //'method' called as a property of 'p.child'
         // but when you call it from KO it's actually 'p' <Parent>
    };
}

function Parent() {
    this.child = new Child();
}
var p = new Parent();
ko.applyBindings(p);

HTML:

 <a href="#" data-bind="click: child.method">foo</a>

Is it bug or a feature I just not understand?

Upvotes: 2

Views: 136

Answers (2)

hutchonoid
hutchonoid

Reputation: 33305

You need to do the following:

function Child() {
    var self = this;
    self.method = function() {
         console.dir(self); // this should be 'p.child' <Child> since 
         //'method' called as a property of 'p.child'
         // but when you call it from KO it's actually 'p' <Parent>
    };
}

function Parent() {
    var self = this;
    self.child = new Child();
}
var p = new Parent();
ko.applyBindings(p);

http://jsfiddle.net/ZuHMY/1/

Please see here for the info on self = this;

What underlies this JavaScript idiom: var self = this?

Update

This also answer's the question about self and this here:

In knockout.js, why "this" is being assigned to "self"?

Upvotes: 1

xdumaine
xdumaine

Reputation: 10329

I don't know this for sure, but it's possible that knockout is attempting to set the context so that you can operate on the parent from within child functions and subscriptions.

This JSFiddle shows how you can change the context of a function call using call(this):

function Child() {
    this.method = function() {
         console.dir(this);
    };
}

function Parent() {
    this.child = new Child();
} 
var p = new Parent();
p.child.method(); // child
p.child.method.call(p); // parent

Upvotes: 0

Related Questions