我目前有一个简单的Value Converter,它使用momentjs
将日期转换为字符串:
export class MomentValueConverter {
public toView(value: Date, format: string): string {
return moment(value).format(format);
}
}
但是,无论我在哪里使用它,我最终都必须将其与aurelia-translation-signal
结合使用,以便在用户更改当前语言时更新它。
${fileSaved | moment:'ll LTS' & signal:'aurelia-translation-signal'}
如何创建一个自动处理来自aurelia-translation-signal
的信令的绑定行为?
然后我可以像:
一样使用它${fileSaved & moment:'ll LTS'}
答案 0 :(得分:1)
aurelia-i18n库中有一个很好的例子,https://github.com/aurelia/i18n/blob/master/src/t.js#L89-L122
import {ValueConverter} from 'aurelia-binding';
import {SignalBindingBehavior} from 'aurelia-templating-resources';
export class TBindingBehavior {
static inject = [SignalBindingBehavior];
constructor(signalBindingBehavior) {
this.signalBindingBehavior = signalBindingBehavior;
}
bind(binding, source) {
// bind the signal behavior
this.signalBindingBehavior.bind(binding, source, 'aurelia-translation-signal');
// rewrite the expression to use the TValueConverter.
// pass through any args to the binding behavior to the TValueConverter
let sourceExpression = binding.sourceExpression;
// do create the sourceExpression only once
if (sourceExpression.rewritten) {
return;
}
sourceExpression.rewritten = true;
let expression = sourceExpression.expression;
sourceExpression.expression = new ValueConverter(
expression,
't',
sourceExpression.args,
[expression, ...sourceExpression.args]);
}
unbind(binding, source) {
// unbind the signal behavior
this.signalBindingBehavior.unbind(binding, source);
}
}
更新:价值转换器已在内部支持信号http://aurelia.io/docs/binding/value-converters#signalable-value-converters
import {signalBindings} from 'aurelia-framework';
signalBindings('locale-changed');
export class FlightTimeValueConverter {
signals = ['locale-changed'];
toView(date) {
return date.toLocaleString(window.currentLocale);
}
}