![](/img/trans.png)
[英]Knockout.js child object only updates when parent is updated and setting values to a child object
[英]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>
是错误还是我不了解的功能?
您需要执行以下操作:
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);
请参阅此处以获取有关self = this;
的信息self = this;
JavaScript惯用语的基础是什么:var self = this?
更新
这也回答了关于自我和这里的问题:
我不确定这一点,但是敲除可能会尝试设置上下文,以便您可以在子函数和订阅中对父项进行操作。
此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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.