Search code examples
extjssencha-touch-2sencha-architect

How to use Ext.create properly


Can't find any relevant information in the sencha documention about this question :

Is it possible to call Ext.create(...) with a parameter which does not depend on the application's name? So that if I change the app's name I don't have to rewrite that line of code?

Normally I would use Ext.create(AppName.model.MYMODEL) but that's too tied to the app's name for me.

Still need help :)


Solution

  • Create using class alias

    When using Ext.define to define your class, you can provide an alias property. You've probably seen this on UI components which use aliases like widget.panel. Those aliases can be used with Ext.create.

    Ext.define('MyApp.SomeClass', {
        alias: 'app.someclass',  // Independent of class name
        /* ... */
    });
    
    Ext.create('app.someclass', {
        /* ... */
    });
    

    You can set the alias on a class after it has been created by using Ext.ClassManager.setAlias.

    Helper function using application name

    If you don't have the option to set an alias, you could create a function that wraps Ext.create which supplies your base namespace automatically.

    The problem here is that Ext.application doesn't return the application object. I'm not sure how Sencha Architect generates the application code but you may need additional overrides to allow you to retrieve the application object.

    function appCreate(className, config) {
        var appName = someMethodThatGetsTheApplicationName();
        return Ext.create(appName + '.' + className, config);
    };
    
    // Example usage: Creates object of MyApp.model.MyModel
    var myObj = appCreate('model.MyModel', { /* ... */ });
    

    How to get the application name at runtime

    By default, Ext JS does not retain a reference to the application object when using Ext.application, so we need an override to do it. I'm using Ext.currentApp as the property to store this object, but you can change it to whatever you'd like.

    Ext.application = function (config) {
        Ext.require('Ext.app.Application');
    
        Ext.onReady(function () {
            Ext.currentApp = new Ext.app.Application(config);
        });
    };
    

    Now that you have this, you can access the application name by simply using Ext.currentApp.name. Or, if you'd feel more comfortable using a getter you can use the following.

    Ext.app.Application.addMembers({
        getName: function () {
            return this.name;
        }
    });
    
    // Example usage:
    function someMethodThatGetsTheApplicationName() {
        if (!Ext.currentApp) {
            Ext.Error.raise('Current app does not exist.');
        }
        return Ext.currentApp.getName();
    }