0

我一直在阅读并尝试使用此线程中提出的方法: 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', { 扩展:'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)总是输出 store 的最新 Record 对象。

我怎样才能解决这个问题 ?

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

4

1 回答 1

0

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

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

于 2012-04-12T09:34:34.790 回答