Aurelia 2自定义元素(已经通过@共享视图)做了几乎相同的事情,如何重构? [英] Aurelia 2 custom elements (already sharing a view via @) doing almost the same thing, how to refactor?

查看:99
本文介绍了Aurelia 2自定义元素(已经通过@共享视图)做了几乎相同的事情,如何重构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is my problem: Aurelia app:

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

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

推荐答案

您在问题中引用的共享"代码是自定义元素中与生命周期相关的内容,它并不真正适合共享.您将需要进行继承,并使用自定义元素来使自己备受困扰.

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.

假设您有一个自定义元素,该元素会在属性更改时调用函数.对于元素的某些实例,此功能需要有所不同.您可以使用可绑定的函数来完成该操作,并使用.call行为,如下所示:

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

这篇关于Aurelia 2自定义元素(已经通过@共享视图)做了几乎相同的事情,如何重构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆