Knockout.js 当$parent.foo是一个原型方法时,这不是父方法,变通方法?

Knockout.js 当$parent.foo是一个原型方法时,这不是父方法,变通方法?,knockout.js,Knockout.js,在我的视图模型中,我有原型方法,其中该上下文是for each中的项,而不是实际的视图模型。我如何做到这一点 <button data-bind="click: $parent.methodThatNeedsAccesToTheParentViewModel">Edit</button> 想法?您的数据绑定中有$parent,因此应该调用父对象上的方法。您的意思是将$data.methods作为数据绑定,它需要访问ParentViewModel吗?如果您这样做了,那

在我的视图模型中,我有原型方法,其中该上下文是for each中的项,而不是实际的视图模型。我如何做到这一点

  <button data-bind="click: $parent.methodThatNeedsAccesToTheParentViewModel">Edit</button>

想法?

您的数据绑定中有$parent,因此应该调用父对象上的方法。您的意思是将$data.methods作为数据绑定,它需要访问ParentViewModel吗?如果您这样做了,那么您需要研究某种pubsub框架,或者

不将函数直接传递给单击绑定,将其包装在匿名函数中,以便在视图模型的上下文中调用它:

<button data-bind="click: function() { $parent.methodThatNeedsAccesToTheParentViewModel() }">Edit</button>
另一方面,通过创建一个匿名函数,您可以在所需对象($parent)的范围内显式调用您的方法,因此被正确绑定


我希望这有点帮助……:)

我也遇到了同样的问题,我用这种方式解决了它:

<button data-bind="click: $parent.methodThatNeedsAccesToTheParentViewModel.bind($parent)">Edit</button>
编辑

您是否在询问如何在方法中实际获取this变量以指向ViewModel实例?或者别的什么?因为该方法是一个原型,所以“this”值不是实例化的视图模型(非原型方法中的normaly=$parent),而是for each中的子对象,这是我不想要的。AFAIK$parent是foreach绑定中的当前项,所以我希望它能工作。有时我想知道遇到这些问题时使用protype有什么意义。您能指出解释函数()如何运行的源代码吗{…给出了正确的上下文?是的,当我骑上自行车回家时,我就想到了这样做!我没有看到太多关于这个表单应用于对象的明确文档,但它大部分可以从匿名函数与函数一起使用的地方删除。@Futuad我在我的回答中添加了一些关于它为什么工作的注释我也喜欢这种语法,我不喜欢在我的视图中看到
function(){…}
东西。
A = function() {
   this.name = "foo";
};
A.prototype.getName = function() { return this.name; };

a = new A();

console.log(a.getName()); // should log "foo" as expected

f = a.getName; // now f contains a reference to the function

console.log(f()); // this call the function in the current scope - most likely the window, and return nothing

b = new Object(); // another generic object - suppose this is knockout binding context

console.log(f.call(b)); // this bind the call explicitly to b, but since b has no name property,  nothing is returned again

console.log(f.call(a)); // this time we bind the function call to an object that has a name proerty, so the correct value is returned
<button data-bind="click: $parent.methodThatNeedsAccesToTheParentViewModel.bind($parent)">Edit</button>