【问题标题】:Two-way binding between parent and child custom element in AureliaAurelia中父子自定义元素之间的双向绑定
【发布时间】:2015-12-02 08:08:50
【问题描述】:

我以为我正在尝试做一些非常简单的事情,但我就是无法完成这项工作。整个示例位于plunkr

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

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

和视图:

<template>
  <div style="border: solid 1pt green;">
    <h2>This is the child</h2>
    This is the child data : ${childData}
  </div>
</template>

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

import {bindable} from "aurelia-framework";
export class App {
  parentData = "this is parent data";
}

和视图:

<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>

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

请强调我的愚蠢 :) 因为目前我一直认为这应该可行。

【问题讨论】:

    标签: aurelia


    【解决方案1】:

    @bindable 的默认约定是使用命名约定 'myProperty' -&gt; 'my-property'(破折号大小写)将驼峰式属性名称转换为属性名称。

    来自documentation

    @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
    })
    

    默认值和约定如上所示。所以,你只需要 如果您需要偏离,请指定这些选项。

    所以你需要在你的 HTML 中写上child-data.bind

    <child-element child-data.bind="parentData"></child-element>
    

    Plunkr

    【讨论】:

    • 好吧,现在我觉得很傻!我知道 dash-casing 的存在,但没有在这种情况下尝试过(facepalm)。 @nemesv - 谢谢 :)
    • 我可以补充一点,文档并没有特别强调这一点。感谢您的回答!
    • 文档链接失效,请更新
    • @samuel.molinski 我猜你会在这里找到你要找的东西:aurelia.io/hub.html#/doc/article/aurelia/templating/latest/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 2015-08-07
    • 2017-11-03
    相关资源
    最近更新 更多