从子级在根上触发方法时的上下文 [英] Context of this when triggering method on root from child
问题描述
我有这个非常简单的测试视图
I have this very simple test view
<button data-bind="click: add">Add</button>
<table data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td><button data-bind="click: $root.remove">Remove</button></td>
<tr>
</table>
提琴: http://jsfiddle.net/6PP5m/
问题在于remove方法中的上下文是触发点击事件的子视图模型
The problem is that the context of this in the remove method is the child view model that fired the click event
我还没有找到我喜欢的解决方案,您可以在构造函数中添加一个自变量,并使用它来代替"this",但是它的代码更干净,并且可以使用"this"关键字来实现
I havent found a solution that I like, you can add a self variable in the contructor and use that instead of "this", but its more clean code and OO to use the "this" keyword
提琴: http://jsfiddle.net/Qn2CM/
您还可以创建一个代理函数委托,但是它的代码仍然不是很干净
You can also create a proxy function delegate but its still not very clean code
小提琴: http://jsfiddle.net/gYhMr/
我想告诉ko以某种方式将此上下文设置为正确的正确范围(在这种情况下为$ root)?
What I would like is to tell ko somehow to set the context of this to the correct correct scope ($root in this case) is it possible?
推荐答案
点击/事件绑定在您发现的当前数据上下文中运行.
The click/event bindings run in the context of the current data as you have found.
有一些选项可确保您的函数在正确的上下文中运行:
There are a few options to ensure that your function runs with the correct context:
- 将正确的
this
设置为类似self
的变量,并在处理程序中使用它(如前所述) - 在视图模型中使用诸如
$.proxy
或.bind
之类的内容,以确保this
是正确的(如您所述) - 像
data-bind="click: $root.remove.bind($root)"
一样内联函数
- 使用
data-bind="click: function() { $root.remove($data); }"
这样的(丑陋的)匿名函数
- set the correct
this
to a variable likeself
and use it in your handler (as you have mentioned) - use something like
$.proxy
or.bind
in your view model to ensure thatthis
is correct (as you have mentioned) - bind the function in-line like
data-bind="click: $root.remove.bind($root)"
- use an (ugly) anonymous function like
data-bind="click: function() { $root.remove($data); }"
这篇关于从子级在根上触发方法时的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!