2014-01-28 24 views
1

JS:knockout.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> 

它是错误或一个功能,我只是不明白?

回答

1

你需要做到以下几点:

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/

请在这里看到的信息上self = this;

What underlies this JavaScript idiom: var self = this?

更新

这也回答是关于自己的问题,这在这里:

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

+0

是的,我知道如何解决这个问题。我只是想知道这是一个错误还是有一些我误解的逻辑(例如LoD的一些应用)? –

+0

你为什么要让自己再次成为一个全球?问心无愧。 – EaterOfCode

+0

@EaterOfCode哎呀,错字。我忘了添加var self,已更新。 :) – hutchonoid

0

我不知道这是肯定的,但它可能是淘汰赛试图设置情境,让您可以在父工作从子功能和订阅中。

JSFiddle演示了如何更改使用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