javascript - Aurelia 可绑定(bind)值转换器( bool 值等)

标签 javascript typescript aurelia

我有这个属性装饰器,它通过转换器运行属性值,所以我可以在 View 模板中使用 some-bindable-value="true":

function valueConverter(converter: Function) {
    return (target: any, key: string) => {


        let definition = Object.getOwnPropertyDescriptor(target, key);
        if (definition) {
            Object.defineProperty(target, key, {
                get: definition.get,
                set: newValue => {
                    definition.set(converter(newValue));
                },
                enumerable: true,
                configurable: true
            });
        } else {
            Object.defineProperty(target, key, {
                get: function () {
                    return this['__' + key];
                },
                set: function (newValue) {
                    this['__' + key] = converter(newValue);
                },
                enumerable: true,
                configurable: true
            });
        }
    }
}

class App {
    @valueConverter(value => value == 'true') public someBooleanValue;

    constructor() {
        this.someBooleanValue = 'false';
        console.log(this.someBooleanValue) // false

        this.someBooleanValue = 'true';
        console.log(this.someBooleanValue) // true
    }

}

只要我不使用 @bindable 装饰器(这使它完全没有意义),这就可以正常工作。我是装饰者的新手,不确定如何使用 Aurelia 的属性观察机制来完成这项工作。

最佳答案

我认为,如果我要尝试完成此操作,我会首先复制 bindable 装饰器的代码,然后向其中添加我自己的代码。它位于此处:https://github.com/aurelia/templating/blob/master/src/decorators.js

查看 observable 装饰器的工作方式也可能会有帮助:https://github.com/aurelia/binding/blob/master/src/decorator-observable.js

看起来您可能不得不亲自动手才能完成您想要的。话虽这么说,如果您能够实现它,我们希望它能作为 PR 回到框架中在某个时候!

关于javascript - Aurelia 可绑定(bind)值转换器( bool 值等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45858558/

相关文章:

javascript - vue-router:嵌套命名 View 问题。附加组件不可见

javascript - 如何在 Google Chrome 中打开没有滚动条的 window.open

javascript - 如何编写合适的算法序列化这种特殊格式的json数据?

javascript - 抓取特定 html 数据时出现问题,或数据未显示

javascript - 按父实体和虚线路径列出的实体列表

typescript - typeorm:保存具有多对多关系 ID 的实体

node.js - 使用自定义属性的 aurelia 自定义插件 - 找不到自定义属性

typescript - 如何在 Aurelia 中使用 BingMaps

typescript - 如何在 addEventListener 上键入 currentTarget

javascript - 将自定义 header 添加到 Aurelia Fetch 请求