当子类视图模型绑定到视图时,它会覆盖继承自的基类中的方法,“ 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>