Aurelia中父级和子级自定义元素之间的双向绑定

Phi*_*hil 24 aurelia aurelia-binding

我以为我试图做一些非常简单的事情,但我无法做到这一点.整个例子都是关于plunkr

我有一个非常基本的自定义元素,@bindable它显示一个数据成员,它显示并监视已更改的事件.它看起来像这样:

import {bindable} from "aurelia-framework";
export class ChildElementCustomElement {  
  @bindable childData;  
  childDataChanged(value) {
    alert("Child Data changed " + value);
  }  
}
Run Code Online (Sandbox Code Playgroud)

和观点:

<template>
  <div style="border: solid 1pt green;">
    <h2>This is the child</h2>
    This is the child data : ${childData}
  </div>
</template>
Run Code Online (Sandbox Code Playgroud)

父级显示子元素,但我希望其视图模型中的成员绑定到子级,因此父成员中的任何更改都会自动反映在子级中.这是父代码:

import {bindable} from "aurelia-framework";
export class App {
  parentData = "this is parent data";
}
Run Code Online (Sandbox Code Playgroud)

和观点:

<template>
  <h1>Two-way binding between parent and child custom elements</h1>
  <require from="./child-element"></require>  
  <child-element childData.bind="parentData"></child-element>  
  <hr/>  
  <label>The following is the parent data:</label>
  <input type="text" value.bind="parentData"></input>  
</template>
Run Code Online (Sandbox Code Playgroud)

我想看到的是输入字段中输入的任何更新都会自动出现在子项中(加上已更改的事件触发),但子项根本没有绑定!我也试过交换bind,two-way以防万一会议已经绑定one-way但仍然没有奏效.

请突出我的愚蠢:)因为目前我一直认为这应该工作.

nem*_*esv 28

默认约定@bindable是使用命名约定'myProperty' -> 'my-property'(dash-casing)将camel-cased属性名称转换为属性名称.

文档:

@bindable({
  name:'myProperty', //name of the property on the class
  attribute:'my-property', //name of the attribute in HTML
  changeHandler:'myPropertyChanged', //name of the method to invoke when the property changes
  defaultBindingMode: bindingMode.oneWay, //default binding mode used with the .bind command
  defaultValue: undefined //default value of the property, if not bound or set in HTML
})
Run Code Online (Sandbox Code Playgroud)

默认值和约定如上所示.因此,如果需要偏离,您只需要指定这些选项.

所以你需要用child-data.bindHTML 写

<child-element child-data.bind="parentData"></child-element>
Run Code Online (Sandbox Code Playgroud)

Plunkr

  • 我可以补充说,文档并没有突出这一点.谢谢你的回答! (2认同)