2015-09-06 102 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

該文檔的鏈接已打破,你可以更新請致電 –

相關問題