如何在视图外部计算Aurela插补表达式? [英] How to evaluate an Aurelia interpolation expression outside a view?

查看:0
本文介绍了如何在视图外部计算Aurela插补表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Aurela中,假设我有一个字符串,其中包含一个内插表达式"Today at ${value | date: 'time'}"和表示{ value: new Date() }的绑定上下文的一些对象。 在视图之外,有没有办法只获取该字符串和该对象,并获得得到的格式化字符串,即"Today at 13:44"

我查看了tests,但它们都涉及创建一个HTML元素、绑定,然后解除绑定-我想知道所有这些可能的性能开销是多少,是否有更容易的方法来实现这一点?如果有一种轻量级的方法只针对上下文对象计算这样的字符串,而不需要设置和拆除绑定等,那就太棒了。

推荐答案

示例:https://gist.run?id=a12470f6e9f7e6a605b3dd002033fdc7

expression-evaluator.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' } } });
  }
}

编辑

我忽略了您需要分析内插表达式,而不是正则绑定表达式...

在Aurela-Validation中有一个这样的示例:https://github.com/aurelia/validation/blob/master/src/implementation/validation-message-parser.ts

这篇关于如何在视图外部计算Aurela插补表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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