小编Jon*_*han的帖子

如何在KnockoutJS中为click事件维护引用正确的执行上下文?

这是一个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";
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图使用'click'绑定绑定此ViewModel.问题是当我的绑定使用$ parent上下文时,我的ViewModel中的'this'值无法解析为ViewModel.

例如,此绑定工作正常:

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

但是,当我使用另一个绑定上下文并尝试使用$ 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> …
Run Code Online (Sandbox Code Playgroud)

javascript javascript-events knockout.js

3
推荐指数
1
解决办法
939
查看次数