2016-04-26 65 views
0

視圖使用Aurelia大街,如何設置一個默認值自定義屬性

<template> 
    <div single-value-attrib="${color}"></div> 
    <div single-value-attrib.bind="color"></div> 
    <input type="text" value.bind="color" /> 
</template> 

視圖模型

export class SingleValueAttribCustomAttribute { 
    static inject = [Element]; 
    color = 'orange'; 
    constructor(element) { 

    this.element = element; 
    this.element.style.width = this.element.style.height = '100px'; 
    } 

    bind() { 
    this.element.style.backgroundColor = this.value; 
    } 

    valueChanged(newValue, oldValue) { 
    this.element.style.backgroundColor = newValue; 
    } 
} 

我期待的是color='orange';在視圖模型將映射到顏色上的觀點從而將默認顏色設置爲橙色。更改輸入框中的顏色按預期工作。我知道你可以設置this.value爲默認顏色,但我只是認爲綁定的工作方式與skeleton-nav中的輸入框具有firstName和lastName的默認值相同。

回答

1

首先,請注意this.color沒有在代碼視圖模型中的任何地方使用,所以設置它在代碼中確實沒有做任何事情。

經過一番遊戲後,我確定在這種特定情況下最好的選擇是設置構造函數中的背景顏色,並去除bind函數。我在這裏創建一個gist.run:https://gist.run/?id=a15e0305f082f6ef080364caff2a1ec1

這裏是虛擬機的自定義屬性:

export class SingleValueAttribCustomAttribute { 
    static inject = [Element]; 
    defaultColor = 'orange'; 
    constructor(element) { 

    this.element = element; 
    this.element.style.width = this.element.style.height = '100px'; 
    this.element.style.backgroundColor = this.defaultColor; 
    } 

    valueChanged(color) { 
    if(color.trim() !== '') { 
     this.element.style.backgroundColor = color; 
    } 
    } 
} 

您可能希望在valueChanged除去在檢查空字符串上color,這取決於你用例。

+0

將顏色更改爲值='橙色'不起作用。在構造函數中設置this.value ='orange'也不起作用,但它應該是合理的。如果我將this.value更改爲this.myvalue並將this.myvalue設置爲'orange',那麼它就可以工作。 – dan

+0

你知道嗎?你是對的。我要更新答案是正確的。 :-) –

+0

完美的作品,謝謝 – dan