gpt4 book ai didi

javascript - 如何为 KnockoutJS 中的单击事件维护引用正确的执行上下文?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:35:30 25 4
gpt4 key购买 nike

这是一个演示我的问题的 jsFiddle:http://jsfiddle.net/dDEd5/4/

总而言之,我有一个简单的 ViewModel:

ViewModel = function () {}
ViewModel.prototype = {
child: function () {},
children: new Array(3),

outermethod: function () {
this.innerMethod();
},

innerMethod: function () {
alert("ok!");
},

outerProperty: function () {
return this.innerProperty();
},

innerProperty: function() {
return "Property is OK";
}
}

我正在尝试使用“点击”绑定(bind)来绑定(bind)此 ViewModel。问题是,当我的绑定(bind)使用 $parent 上下文时,我的 ViewModel 中“this”的值无法解析为 ViewModel。

例如,这个绑定(bind)工作正常:

<div>
<span data-bind="text: outerProperty()"></span>
<button data-bind="click: outermethod">This Works</button>
</div>

但是,当我使用另一个绑定(bind)上下文并尝试使用 $parent 调用我的 ViewModel 时,事情就崩溃了。在以下两个示例中,属性解析良好;然而,按钮都出错了:

<div>
<!-- ko with: child -->
<span data-bind="text: $parent.outerProperty()"></span>
<button data-bind="click: $parent.outermethod">This Doesn't</button>
<!-- /ko -->
</div>

<div>
<!-- ko foreach: children -->
<span data-bind="text: $parent.outerProperty()"></span>
<button data-bind="click: $parent.outermethod">These Don't Either</button>
<!-- /ko -->
</div>

我尽职尽责地试图了解执行上下文在 javascript 中的工作原理以及这些示例失败的原因;但是,我对此不知所措。

最佳答案

当 Knockout 执行处理程序时,它使用绑定(bind)在该级别的当前数据作为上下文。因此,当使用诸如 $parent$root 之类的东西时,这可能会导致问题。

有几种处理方法:

-您可以将其绑定(bind)到绑定(bind)本身中的适当上下文,例如:

`click: $parent.outermethod.bind($parent)`

这将返回一个新函数,确保 $parent 将是 this

- 你可以在你的 View 模型中绑定(bind)它。由于您将函数放在原型(prototype)上,因此更具挑战性。

一种技术(不使用原型(prototype))是使用变量来跟踪 this 的正确值并在您的函数中引用它,例如:

var ViewModel = function() {
var self = this;

this.outermethod = function() {
self.innerMethod();
};

};

使用原型(prototype),您仍然可以将实现放在原型(prototype)上,然后在实际实例上创建绑定(bind)版本,如:

var ViewModel = function() {
this.outermethod = this.outermethod.bind(this);
};

因此,这将在实例上创建一个新函数,该函数使用正确的上下文调用原型(prototype)的函数实现。

关于javascript - 如何为 KnockoutJS 中的单击事件维护引用正确的执行上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14391668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com