2

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?

hutchonoid
  • 31,459
  • 14
  • 91
  • 100
Roman Bekkiev
  • 2,462
  • 1
  • 18
  • 27

2 Answers2

1

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"?

Community
  • 1
  • 1
hutchonoid
  • 31,459
  • 14
  • 91
  • 100
0

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
xdumaine
  • 8,428
  • 6
  • 50
  • 99