Sencha touch 2.0:使用商店进行自定义模型验证

时间:2012-04-11 10:57:42

标签: validation sencha-touch-2

我一直在阅读并尝试使用此主题中提出的方法: How to add a custom validation rule to a model in Sencha Touch

首先,我将自定义验证类型添加到Ext.data.validations单例:

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";
}

然后,由于我正在使用ST2,我应用Ben G提出的建议。我扩展Ext.data.Model以包含对'self'(this)的引用。

Ext.define('MyApp.model.CustomModelBase',{         extend:'Ext.data.Model',

    //adding an initializer to let custom validators access "self"
    init : function () {
        var i, len;
        if (this.config.validations) {
            for (i = 0, len = this.config.validations.length; i < len; i++) {
                this.config.validations[i].self = this;
            }
        }
    }
});

最后,我创建了一个扩展CustomModelBase的模型。我们称这个模型为MyApp.model.MyModel。我在其中定义了一个自定义验证规则。

Ext.define('MyApp.model.MyModel', {
    extend: 'MyApp.model.CustomModelBase',
    config: {
        fields: [ {name:'field1'} ],

        validations: [
            { 
                type: 'custom', field: 'field1', message: "Your field is bad",
                fn: function (value) {
                     **console.log(this);**
                   return (value>0);
                }
            }           
        ],

        proxy: {
            type: 'localstorage',
            id  : 'MyApp-Local-Storage'
       }        
    }
});

现在,当只创建一个MyModel实例时,一切正常。

问题是当我存储了MyModel时。当你这样做时,fn函数中收到的'this'的引用似乎总是商店中的最新项。 更准确地说, console.log(this)总是输出商店的最新Record对象。

我该如何解决这个问题?

更新: 我想知道是不是因为所有的商店记录共享同一个模型实例? 我们可以对此做些什么,或者上述整个方法是否无法使用商店?

1 个答案:

答案 0 :(得分:0)

我找到了这个解决方案(在Sencha Touch 1.0论坛中,但它在ST2中对我有用): http://www.sencha.com/forum/showthread.php?122680-Conditional-fields-validations

它需要覆盖Model类的validate()方法,但如果你不介意,那么这比我之前公开的更容易......