Javascript 手动创建计算属性
问题就在这里。我目前正在创建一个mixin来处理表单验证。问题是我想在init方法中创建一个computed属性Javascript 手动创建计算属性,javascript,ember.js,Javascript,Ember.js,问题就在这里。我目前正在创建一个mixin来处理表单验证。问题是我想在init方法中创建一个computed属性isFormValid,它是一个'computed.and'属性'isValid'其他属性 我可以创建它,但它永远不会更新。我想我需要添加观察员,但也许有人会有更好的解决方案 编辑 这里有一些澄清 我的控制器得到了那个属性: App.FormViewController = Ember.Controller.extend(App.ValidatorMixin, { valida
isFormValid
,它是一个'computed.and'
属性'isValid'
其他属性
我可以创建它,但它永远不会更新。我想我需要添加观察员,但也许有人会有更好的解决方案
编辑这里有一些澄清 我的控制器得到了那个属性:
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
属性应该是一个Ember.computed.and
所有这些isValid
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
}
});
在
init
方法中,可以使用defineProperty
设置计算属性
Ember.defineProperty(myObject, 'myProperty', Ember.computed(function computed() {
return 'myValue';
}).property('myObserver'));
这对你有用吗?(正在扩展@Wildhoney,我无法评论)。如果有多个属性,则可以指定多个属性:
Ember.defineProperty(myObject, 'myProperty', Ember.computed(function computed() {
return 'myValue';
}).property('myObserver.@each.myObservedProperty'));
我在Ember中使用jQuery Validate时运气不错,它触发了表单视图的.Validate()调用和diInsertElement上的规则,然后在焦点离开每个Ember.TextField时进行.valid()检查。我强烈推荐它用于表单验证。我不能这样做,因为
myObserver
是一个动态生成的值数组。我也可以做this.set('isFormValid',Ember.computed(…).property())
这是第一次设置它,但在相关键更新时不更新。那么myObserver.length
怎么样,这样它会在每次更新数组时触发呢?您还有myObserver。@每个都会做大致相同的事情。不幸的是,它不起作用,因为我不更新数组,而是更新数组引用的属性。
Ember.defineProperty(myObject, 'myProperty', Ember.computed(function computed() {
return 'myValue';
}).property('myObserver.@each.myObservedProperty'));