Aurelia 2 个自定义元素(已经通过@共享一个视图)做几乎相同的事情,如何重构?

Aurelia 2 custom elements (already sharing a view via @) doing almost the same thing, how to refactor?

这是我的问题: Aurelia 应用程序:

一些自定义元素(已经通过@UseView 共享一个视图)做几乎相同的事情(特定功能应该由每个元素本身定义),如何管理共享代码(inkl @bindable)? 如何重构这个: https://gist.run/?id=897298ab1dad92fadca77f64653cf32c

您在问题中提到的 "shared" 代码是自定义元素中与生命周期相关的内容,不适合共享。您将需要进行继承,并且使用自定义元素会让您很头疼。

与其共享代码,不如关注可变的东西并尝试使它们可配置?通过查看您的要点,这似乎是迄今为止最直接的解决方案。

假设您有一个自定义元素,它在 属性 发生变化时调用一个函数。对于元素的某些实例,此函数需要不同。您可以使用可绑定函数完成此操作,并使用 .call 行为,如下所示:

一些-element.js

import { bindable } from 'aurelia-framework';

export class SomeElement {

    @bindable value;
    @bindable processValue;

    valueChanged(newValue, oldValue) {
        if (this.processValue) {
            this.processValue({ val: newValue });
        }
    }
}

consumer.html

<some-element value.bind="myValue" process-value.call="myFunc(val)"></some-element>
<some-element value.bind="anotherValue" process-value.call="anotherFunc(val)"></some-element>

consumer.js

myFunc(val) {
    console.log("val: " + val);
}

anotherFunc(val) {
    console.log("val: " + val);
}