【问题标题】:Aurelia with Typescript: binding using properties doesn't workAurelia 与 Typescript:使用属性绑定不起作用
【发布时间】:2016-12-02 23:57:32
【问题描述】:

我在 Aurelia 中有一个使用 Typescript (2.0) 的自定义元素,并且想要绑定一些值,但它不起作用。这是我的例子:

myelement.html:

<template>
  <div>${caption}</div>
  <div>${unit}</div>
 </template>

myelement.ts:

import { bindable } from "aurelia-framework";

export class MyElement {
    // removing the @bindable doesn't change anything
    @bindable public caption: string;
    @bindable public unit: string;
}

用法:

<require from="./myelement"></require>
...
<myelement caption.bind="currentvalue" unit=" km"></myelement>

currentvalue 属性定义为(在使用自定义元素的类中)

public currentvalue: number = 11;

myelement 被正确插入,但是占位符被替换为空文本(即被删除),甚至只是一个文本的“单元”。

“单位”占位符的有趣之处在于:

myelement.html:

<template bindable="unit">
  <div>${caption}</div>
  <div>${unit}</div>
 </template>

在这种情况下,${unit} 被替换为“km”。

不知何故,Aurelia 无法在自定义元素的 html 和视图模型之间建立联系。使用 bindable 属性进行绑定有效,但前提是它未绑定到属性。 myelement.js 文件被正确加载(我将 SystemJS 与 AMD 模块一起使用)。 我错过了什么?

更新:

我在 myelement.ts 中将 @bindable 更改为 @bindable(),现在“单位”已正确绑定 - 模板中的占位符已正确替换为“km”。但是使用属性的绑定(在我的例子中是标题)仍然不起作用。

更新 2: 最后我让它工作了。使用 &lt;require from="./myparentelement.html"&gt; 包含父自定义元素(使用 myelement),因此未附加其视图模型...

【问题讨论】:

  • 我认为你的元素名称应该是 &lt;my-element&gt; 而不是 &lt;myelement&gt; 因为 Aurelia 默认使用连字符分隔每个新的大写单词的类名称。尝试更改您使用中的元素,看看它是否有所作为。或者将您的班级名称从 MyElement 更改为 Myelement
  • 尝试用括号编写@bindable()。不久前,我读到了一些关于 TypeScript 中的错误,当 () 丢失时会导致奇怪的行为。此外,您将 unit 绑定到“km”,并且似乎希望字符串能够通过 UI,但在这种情况下,km 将被解释为属性。创建一个单位属性并将其值设置为“km”,然后绑定到该属性
  • @LStarky 这有助于加载正确的文件,但不能用于绑定。
  • @mgiesa 这有助于绑定常量值(耶!),但不是属性绑定...

标签: typescript aurelia


【解决方案1】:

没有正确要求父自定义元素: &lt;require from="./myparentelement.html"&gt; 而不是 &lt;require from="./myparentelement"&gt;,我不得不使用 @bindable() 而不是 @bindable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2021-12-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多