Where should I define global functions in ExtJS 4 MVC?

14,461

Solution 1

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);
    }
});

Solution 2

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.

Share:
14,461

Related videos on Youtube

Julian Hollmann
Author by

Julian Hollmann

I'm a passionate Software Engineer, Tinkerer and Entrepreneur on a mission to make the web a better place.

Updated on June 06, 2022

Comments

  • Julian Hollmann
    Julian Hollmann almost 2 years

    I need to define some functions which i can call everywhere in my app. What is the best approach to achieve this?

  • s.webbandit
    s.webbandit almost 12 years
    Can you provide some little example of your idea?
  • JohnnyHK
    JohnnyHK almost 12 years
    Shouldn't the Utilities.foo call be MyApp.Utilities.foo?
  • Kirill
    Kirill almost 12 years
    That's what I get for changing the namespace at the last minute. Fixed, thanks.
  • darren
    darren over 11 years
    Great answer. As a side note in Sencha Architect you can add the utility class JS file as a Resource to the project.
  • Raza Ahmed
    Raza Ahmed almost 11 years
    What if not want to return anything??
  • A.W.
    A.W. over 9 years
    Cool solution! I put it in /util/ folder
  • Handsome Nerd
    Handsome Nerd over 9 years
    @RazaAhmed What do you mean? The function in the example is not a void method.