在我的视图模型中,我有原型方法,其中此上下文是for each中的项目,而不是实际的视图模型.我该如何实现这一目标?
<button data-bind="click: $parent.methodThatNeedsAccesToTheParentViewModel">Edit</button>
Run Code Online (Sandbox Code Playgroud)
视图模型:
ViewModel.prototype.methodThatNeedsAccesToTheParentViewModel= function () {
this = duff //this is the item in the foreach, not the real parent
};
Run Code Online (Sandbox Code Playgroud)
想法?
Gri*_*rim 13
不要将函数直接传递给click绑定,将其包装在匿名函数中,以便在视图模型的上下文中调用它:
<button data-bind="click: function() { $parent.methodThatNeedsAccesToTheParentViewModel() }">Edit</button>
Run Code Online (Sandbox Code Playgroud)
这样,当绑定被激活时,它将使用$ parent作为调用的上下文 - 即这
值得注意的是(因为我们看不到文件绑定的结构)$ parent变量将引用当前正在迭代的项之前的绑定,这不一定是对象图中项的父级.
编辑:我错过了上面的一些括号...
编辑2:由于解析绑定的方式,这是有效的.当通过敲除应用绑定时,表达式被解析并且必须求值为函数(因此当你直接绑定到函数时,不需要括号).然后在激活单击绑定时调用此函数.
但是这里有捕获,因为原型javascript中的this关键字不受函数所有者的约束(即定义它的位置),而是取决于调用它的方式(在mozilla文档中更好地解释)在这种情况下敲除调用函数不是通过拥有它的对象(它将正确绑定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
Run Code Online (Sandbox Code Playgroud)
另一方面,通过创建匿名函数,您将在所需对象($ parent)的范围内显式调用您的方法,因此这是正确绑定的.
我希望有点帮助... :)
我有同样的问题,我以这种方式解决了它:
<button data-bind="click: $parent.methodThatNeedsAccesToTheParentViewModel.bind($parent)">Edit</button>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1806 次 |
| 最近记录: |