不要将函数直接传递给点击绑定,将其包装在一个匿名函数中以便在视图模型的上下文中调用它:
<button data-bind="click: function() { $parent.methodThatNeedsAccesToTheParentViewModel() }">Edit</button>
这样,当绑定被激活时,它将使用 $parent 作为调用的上下文 - 即 this
值得注意的是(因为我们看不到文件绑定的结构)$parent 变量将引用当前项目之前的 binding迭代,它不一定是对象图中项目的父项。
编辑:我在上面遗漏了一些括号...
编辑 2:由于绑定的解析方式,此方法有效。当通过敲除应用绑定时,表达式被解析并且必须评估为 function (因此当您直接绑定到函数时不需要括号)。然后当点击绑定被激活时调用这个函数。
但这里有一个问题,因为原型 javascript 中的 this 关键字不受函数所有者的约束(即在哪里定义),而是在调用它的方式上(如解释在mozilla documentation 中更好)在这种情况下敲除调用函数不是通过拥有它的对象(这将正确绑定 this 运算符),而是将其显式绑定到其当前绑定上下文(因为它不能可能知道该函数最初是哪个实例)。您可以通过获取对您的函数的引用,然后在调用时将其绑定到另一个对象来复制此行为 - 一个示例:
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
另一方面,通过创建一个匿名函数,您在所需对象 ($parent) 的范围内显式地 调用您的方法,因此 this 被正确绑定.
希望对你有所帮助... :)