我认为这是文档中的小错误之一。我通过添加一些代码让它们工作
if (Ext.data) {
Ext.data.validations.custom = function (config, value) {
if (config && Ext.isFunction(config.fn)) {
//this should be the model
if (config.self) {
return config.fn.call(config.self, value);
} else {
return config.fn(value);
}
}
else
{
return false;
}
};
Ext.data.validations.customMessage = "Error";
}
然后要向模型添加验证,请将对象添加到模型的验证数组,类型设置为“自定义”,例如
{
type: 'custom', field: 'SomeField', message: "Your field is bad",
fn: function (SomeFieldValueForThisInstance) {
//Add some validation code. The this pointer is set to the model object
//so you can call this.get("SomeOtherFieldToCheck")
//or any other instance method
//if the field is good
return true;
//else
return false;
}
}
更新: @salgiza 是对的,为了正确设置“this”指针,我忘记了几个步骤。如果您查看 sencha touch 代码,您会看到在 Ext.data.Model 的构造函数的末尾,它会检查对象上是否定义了 init 函数,如果有,则调用它
if (typeof this.init == 'function') {
this.init();
定义模型后,您可以向原型添加一个 init 函数。在函数中,遍历对象的验证并添加对 this 的引用。此步骤应在创建任何模型之前完成。
YourModel.prototype.init = function () {
var i, len;
if (this.validations) {
for (i = 0, len = this.validations.length; i < len; i++) {
this.validations[i].self = this;
}
}
};
然后在上面的自定义验证函数中,只要检查配置是否有一个self指针,如果有,用self调用它。我已将上面的代码编辑为使用 self。
注意:我没有看到模型的 init 函数记录在案,所以如果 sencha 摆脱它,您必须以其他方式将 this 指针添加到模型的验证中。 p>
抱歉,如果这引起了任何人的困惑。