2014-01-28 63 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