I've been reading and trying to use the method proposed in this thread: How to add a custom validation rule to a model in Sencha Touch.
So first, I add a custom validation type to the Ext.data.validations singleton:
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";
}
Then, since I am using ST2, I apply what Ben G proposes. I extend Ext.data.Model to include a reference to '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;
}
}
}
});
Finally, I create a model extending the CustomModelBase. Let's call this model MyApp.model.MyModel. I define a custom validation rule inside it.
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'
}
}
});
Now, everything works well when only one instance of MyModel is created.
The problem is when I have store of MyModel's. When you do that, the reference to 'this' received in the fn function seems to always be the latest item in the store. More precisely, the console.log(this) always outputs the latest Record object of the store .
How can I fix this ?
update: I wonder if it's not because all the store records share the same model instance ? Can we do something about it or does the whole method described above fail for using stores ?