在 Aurelia 中,假设我有一个包含插值表达式的字符串"Today at ${value | date: 'time'}"
和一些代表绑定上下文的对象{ value: new Date() }
。
有没有办法在视图之外只获取该字符串和该对象,并获取结果格式化字符串,即"Today at 13:44"
?
我看了看tests https://github.com/aurelia/templating-binding/blob/master/test/interpolation-binding.spec.js,但它们都涉及创建 HTML 元素、绑定,然后解除绑定 - 我想知道所有这些的性能开销可能是多少,以及是否有更简单的方法来实现这一点?如果有一种轻量级的方法来仅针对上下文对象评估这样的字符串,而不需要设置和拆除绑定等,那真是太棒了。
这是一个例子:https://gist.run?id=a12470f6e9f7e6a605b3dd002033fdc7 https://gist.run?id=a12470f6e9f7e6a605b3dd002033fdc7
表达式评估器.js
import {inject} from 'aurelia-dependency-injection';
import {ViewResources} from 'aurelia-templating';
import {Parser, createOverrideContext} from 'aurelia-binding';
@inject(Parser, ViewResources)
export class ExpressionEvaluator {
constructor(parser, resources) {
this.parser = parser;
this.lookupFunctions = resources.lookupFunctions;
}
evaluate(expressionText, bindingContext) {
const expression = this.parser.parse(expressionText);
const scope = {
bindingContext,
overrideContext: createOverrideContext(bindingContext)
};
return expression.evaluate(scope, this.lookupFunctions);
}
}
app.js
import {inject} from 'aurelia-dependency-injection';
import {ExpressionEvaluator} from './expression-evaluator';
@inject(ExpressionEvaluator)
export class App {
message = 'Hello World!';
constructor(evaluator) {
this.message = evaluator.evaluate('foo.bar.baz | test', { foo: { bar: { baz: 'it works' } } });
}
}
Edit
我错过了你需要解析一个事实插值法表达式,不是正则绑定表达式...
aurelia-validation 中有一个这样的例子:https://github.com/aurelia/validation/blob/master/src/implementation/validation-message-parser.ts https://github.com/aurelia/validation/blob/master/src/implementation/validation-message-parser.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)