0

当子类视图模型绑定到视图时,它会覆盖继承自的基类中的方法,“ knockout.command ”似乎正在调用基方法而不是子覆盖方法。

这是 javascript 中的 jsfiddle,尽管我使用的是打字稿。

请注意一个普通的旧点击绑定警报“子操作”,而 knockout.command 警报“基本操作”。我怎样才能使它正确地调用被覆盖的子方法?

打字稿:

class BaseVm {

    public commandAction: any;

    constructor() {
        this.commandAction = ko.asyncCommand({ execute: this.action, canExecute: (isExecuting) => true });
    } 
    public clickAction = () => {
        this.action(null, null, null);
    }
    public action = (val, event, complete) => {
        alert("base action");
    }
}

class ChildVm extends BaseVm {
    constructor() {
        super();
    }
    public action = (loc, event, complete) => {
        alert("child action");
    }
}

ko.applyBindings(new ChildVm());

HTML:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TEST</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/CodeSeven/KoLite/master/knockout.command.js"></script>
    <script type="text/javascript" src="app.js"></script>
</head>
<body>

    <button data-bind="command: { click: $root.commandAction }">COMMAND</button>
    <button data-bind="click: $root.clickAction">CLICK</button>
    <script>
        ko.applyBindings(new ChildVm());
    </script>
</body>
</html>
4

1 回答 1

1

问题不在于上下文,而是基类构造函数在派生类构造函数之前运行,而派生类构造函数action被派生类实现覆盖。

这行代码运行的时候,this.action依然是引用基类实现,值就是在那一刻被抓到的。

constructor() {
    this.commandAction = ko.asyncCommand({ execute: this.action, canExecute: (isExecuting) => true });
} 

您可以改为编写此代码以动态获取 的值this.action

constructor() {
    this.commandAction = ko.asyncCommand({ execute: (a, b, c) => this.action(a, b, c), canExecute: (isExecuting) => true });
} 
于 2015-07-06T22:04:06.630 回答