I need to define some functions which i can call everywhere in my app. What is the best approach to achieve this?
Asked
Active
Viewed 1.5k times
2 Answers
48
Personally, to keep it as EXT-MVC as possible, I have a Utilities class full of static methods. This can be required like any other class to maintain proper dependency relations. This also ensures that the methods are run in an EXT environment, so all of EXT is available.
Ext.define('MyApp.Utilities', {
statics: {
foo: function (a, b) {
return a + b;
}
}
});
Ext.define('MyApp.MyView', {
extends: 'Ext.panel.Panel',
requires: ['MyApp.Utilities'],
initComponent: function () {
MyApp.Utilities.foo(1, 2);
}
});

David Kanarek
- 12,611
- 5
- 45
- 62
-
Can you provide some little example of your idea? – s.webbandit Jul 06 '12 at 05:29
-
2Shouldn't the `Utilities.foo` call be `MyApp.Utilities.foo`? – JohnnyHK Jul 06 '12 at 15:39
-
That's what I get for changing the namespace at the last minute. Fixed, thanks. – David Kanarek Jul 06 '12 at 15:56
-
Great answer. As a side note in Sencha Architect you can add the utility class JS file as a Resource to the project. – darren Oct 29 '12 at 15:47
-
What if not want to return anything?? – Raza Ahmed Jun 27 '13 at 05:31
-
Cool solution! I put it in `/util/` folder – A.W. Oct 24 '14 at 17:47
-
@RazaAhmed What do you mean? The function in the example is not a void method. – Handsome Nerd Jan 10 '15 at 05:19
7
An alternative way other than @David Kanarek's statics approach is to define a singleton. Codes:
Ext.define('MyApp.Utilities2', {
singleton: true,
global_var2: 'Hello World',
foo2: function (a, b) {
return a + b;
},
});
I've created a fiddle here: https://fiddle.sencha.com/#fiddle/qu1
The difference between the statics and singleton approach is that
- MyApp.Utilities2 (singleton approach) is an object,
- MyApp.Utilities (statics approach) is a class.
So It's up to you whether to reference the class itself or to reference one instance of that class for convenience.

gm2008
- 4,245
- 1
- 36
- 38