【问题标题】:Sencha touch 2.0 : Custom model validation with storesSencha touch 2.0:使用商店的自定义模型验证
【发布时间】:2012-04-11 10:57:41
【问题描述】:

我一直在阅读并尝试使用此线程中提出的方法: 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 对象。

我该如何解决这个问题?

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

【问题讨论】:

    标签: validation sencha-touch-2


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      相关资源
      最近更新 更多