2015-09-06 72 views
23

我以为我试图做一些非常简单的事情,但我无法完成这项工作。这整个例子是在plunkrAurelia中父母和孩子自定义元素之间的双向绑定

我有一个非常基本的自定义元素,提出了一个@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> 

我想看到的是在输入栏中输入的任何更新,会自动出现在孩子(加改变的事件触发)但是这个孩子根本没有出现!我也试过换two-way,以防万一约定one-way,但仍然没有奏效。

请突出我的愚蠢:)因为目前我坚持认为这应该只是工作。

回答

27

@bindable的默认约定是使用命名约定'myProperty' -> '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

+0

好了,现在我觉得自己傻了!我知道破折号的外壳的存在,但没有在这方面尝试过(facepalm)。 @nemesv - 谢谢:) – Phil

+2

我可以补充一点,文档不会强调这一点。感谢你的回答! –

+0

该文档的链接已打破,你可以更新请致电 –