PDA

View Full Version : Best way to reuse a function across xtype: Model



iamcootis
18 Jul 2013, 5:28 AM
I have several models that have a date field and that date field needs to be converted. In each place it needs to be converted, I have written out the complete function instead of reusing the same function. I have tried almost everything and nothing worked.

1. I tried to create a mixin class with the function, but it would always break when I tried to call the function.
2. I tried creating and abstract Model class, but the same thing would happen.
3. I tried using a Util controller that contain the function and would try to access the controller first, but that didn't work either.

Is there some reason why none of these things worked? Is it impossible to do what I'm trying to do?

skirtle
18 Jul 2013, 6:06 AM
It's a bit difficult to say but I'd guess your code looks like this?


Ext.define('MyModel', {
extend: 'Ext.data.Model',

fields: [
{name: 'begin', convert: this.dateConverter}
],

dateConverter: function(v) {
...
}
});

This can't work because the value of this will be the global window object at the point the fields config is created.

Likewise the mixin and abstract class approach would have the same problem.

Something like this would work:


MyApp.dateConverter = function(v) {
...
};

...

Ext.define('MyModel', {
extend: 'Ext.data.Model',

fields: [
{name: 'begin', convert: MyApp.dateConverter}
]
});

The key here is that dateConverter must be created before the call to Ext.define. Using requires won't help you, it's already too late. In practice this means you must ensure the file containing dateConverter is loaded before the files that create your models.

An alternative would be to use a custom field type:

http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.Field-cfg-type

However, even with this approach you'd need to ensure the type is created before you try to use it in an Ext.define.

eric.cook
18 Jul 2013, 6:46 AM
An alternative would be to use a custom field type:

http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.Field-cfg-type

However, even with this approach you'd need to ensure the type is created before you try to use it in an Ext.define.

This is the approach that I would recommend. The process is very simple.



Ext.applyIf(Ext.data.Types, {
MYDATE: {
type: 'mydate',
sortType: Ext.data.SortTypes.asDate,
convert: function (v) {
// Your custom convert function
}
}
});

Ext.define('MyModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'begin', type: 'mydate'}
]
});


Now your custom date type can be used by any model in your application, as long as you declare your new type before creating the model of course.