Singleton in ExtJs4

extjsextjs4singleton

I want to create a singleton object in Ext JS 4.

Here is my code:

Ext.define('AM.model.Test', {
    extend : 'Ext.util.Observable',
    singleton : true,
    foo : function() {
        console.log('log 1');
    },
    constructor : function() {

    }
});

I call it with:

AM.model.Test.foo();

It all works fine as long as I place define in app.js.
When I try to move this definition to 'app\model\Test.js' I get this error:

AM.model.Test is undefined [Break On This Error]
AM.model.Test.foo();

What's wrong with my code?

Best Solution

You need to set up the dynamic loading and require the class from where you're intending to use it.

For example:

Ext.Loader.setConfig({
    enabled: true,
    paths: {
        'AM': 'app'
    }
});

Ext.require('AM.model.Test');

Ext.onReady(function() {
    // now all the required classes are loaded and you can start using them
    AM.model.Test.foo();
});
Related Question