一种方法是添加具有计算属性的类名绑定
//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"}}
重要
上面的代码可能会满足您的需要,但如果有很多文本字段,可能会减慢您的应用程序,因为计算属性会针对值的每一次更改执行,最好有一个保存按钮操作,单击时可能会应用文本字段的 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);
}
}