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

时光毁灭记忆、已成空白 提交于 2019-12-25 04:37:22

问题


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


来源:https://stackoverflow.com/questions/39723769/aurelia-2-custom-elements-already-sharing-a-view-via-doing-almost-the-same-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!