gpt4 book ai didi

javascript - KoLite Knockout.command 与继承类的上下文不正确

转载 作者:行者123 更新时间:2023-12-03 09:38:30 25 4
gpt4 key购买 nike

当子类 View 模型绑定(bind)到 View 时,它会重写继承自的基类中的方法,“knockout.command ”似乎正在调用基方法而不是子重写方法。

Here is a jsfiddle在 javascript 中,尽管我使用的是 typescript。

请注意,普通的旧点击绑定(bind)会提醒“子操作”,而knockout.command会提醒“基本操作”。如何才能正确调用重写的子方法?

typescript :

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>

最佳答案

问题不在于上下文,而是基类构造函数在派生类构造函数之前运行,并且在派生类构造函数中,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 });
}

关于javascript - KoLite Knockout.command 与继承类的上下文不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31256322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com