我有这个属性装饰器,它通过转换器运行属性值,所以我可以在 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/