2012-11-20 60 views
1

我想在它的值無效時自動突出顯示一個Ember.TextField。綁定到TextField的類

我有這樣的事情在我的模板現在的作品,但醜:

{{#if view.fieldInvalid}} 
    {{view Ember.TextField valueBinding="view.fieldValue" classNames="span1p5 highlight"}} 
{{else}} 
    {{view Ember.TextField valueBinding="view.fieldValue" classnames="span1p5"}} 
{{/if}} 

有沒有辦法在Ember.JS做到這一點,內置鑑於樣Ember.TextField?

回答

5

這樣做是添加一個類名綁定與計算性能

//First extend Ember.TextField in your view 
validatingTextField = Ember.TextField.extend({ 
    //Now if isInvalid is true CSS class "highlight" is applied to text field 
    /* other ways include 
    isValid::error-class error-class will be applied when isValid is false 
    isValid:normal-class:error-class, normal-class is applied when isValid is true else error-class is applied 
    */ 
    classNameBindings: ['isInvalid:highlight',':span1p5'], 
    //If you have static classes you define them as :my-class-name 
    isInvalid: function(){ 
    if(this.get('value').trim() === ""){ 
     return true; 
    }else{ 
     return false; 
    } 
    }.property('value') 
}) 

現在用你的車把

{{view view.validatingTextField valueBinding="view.fieldValue"}} 

重要上面定義的一種方法 上面的代碼可能會滿足您的需求但如果有許多文本字段可能會減慢應用程序的速度,因爲對於值的每次更改都會執行計算屬性,所以最好有一個保存按鈕操作, k可以將CSS類應用於文本框如下

validatingTextField = Ember.TextField.extend({ 
    classNameBindings: ['isInvalid:highlight',':span1p5'] 
}) 

save: function(){ 
    //your code for save 
    if(this.get('validatingTextField.value').trim()===""){ 
    this.get('validatingTextField').set('isInvalid', true); 
    } 
}