【发布时间】:2014-04-30 14:39:36
【问题描述】:
这就是问题所在。我目前正在创建一个 mixin 来处理表单验证。问题是我想在 init 方法中创建一个计算属性isFormValid,它是'is<fieldName>Valid' 其他属性的'computed.and' 属性。
我可以创建它,但它永远不会更新。我想我需要添加观察者,但也许有人会有更好的解决方案?
编辑
这里有一些说明。
我的控制器获得了该属性:
App.FormViewController = Ember.Controller.extend(App.ValidatorMixin, {
validations: {
field1: {
errLvl: App.Validation.ErrLvl.ERROR,
type: App.Validation.Type.TEXT,
pattern: /^\d{6}$/,
message: 'Error message'
},
field2: {
//somecode
}
}
});
mixin 定义如下:
App.ValidatorMixin = Ember.Mixin.create({
init: function() {
this._super();
var self = this;
Ember.keys(this.validations).forEach(function(prop) {
self.set('is' + prop.capitalize() + 'Valid', false); //Is changed when the field is valid
});
}
});
isFormValid 属性应该是所有这些 is<fieldName>Valid 中的一个 Ember.computed.and
EDIT2
表单上的每个输入都由输入助手和这个 mixin 定义:
App.Mixin.ValidatableInput = Ember.Mixin.create({
focusOut: function() {
this.validate();
},
//Do the validation
validate: function() {
//I'm currently moving that part to the controller because it's part
//of the logic but it was easier for a start to write it here
//We update the is<fieldName>Valid property
this.get('parentView.controller').set('is' + this.get('name').capitalize() + 'Valid', !hasError);
//Then some DOM manipulation to attach the error message
}
});
最后我的看法是这样的
{{view App.CustomTextField name="field1" value=field1}}
{{view view.buttonCreate disabled=isFormInvalid}}
【问题讨论】:
标签: javascript ember.js