Aurelia 2 custom elements (already sharing a view

2019-09-03 20:06发布

问题:

Here is my problem: Aurelia app:

a few custom elements (already sharing a view via @UseView) doing almost the same thing (specific func shoud be defined by every element itself), how to manage shared code (inkl @bindable)? How to refactor this: https://gist.run/?id=897298ab1dad92fadca77f64653cf32c

回答1:

The "shared" code you refer to in your question is lifecycle-related stuff in your custom elements, which isn't really suited for sharing. You would need to do inheritance, and with custom elements that's setting yourself up for a lot of headaches.

Rather than sharing code, why not focus on the things which are variable and try to make them configurable? By looking at your gist, that seems by far the most straightforward solution here.

Say you have a custom element that calls a function when a property changes. This function needs to be different for some instances of the element. You could accomplish that with a bindable function, and use the .call behavior, like so:

some-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);
}