3
votes

I have array of names

 var names = ['X', 'Y'] 

For each name i want to create class instance but only if proper js file exists otherwise function should return null

    getTool:function(name) {

        var t = Ext.create('VC.tools.' + name + 'Tool',{
            map:this.map
        });

        return t.getEntryPoint();
}

Or maybe is there a way of implementing some kind of try catch? I just dont want any errors like file could not be loaded etc.

EDIT:

If i add try catch i can avoid is not a constructor error. But still got file not exists error. Is there a way of handling this?


    try {
                var t = Ext.create('VC.tools.' + name + 'Tool',{
                    map:this.map
                });

                return t.getEntryPoint();

            }catch(err){
                return null;
            }

5

5 Answers

2
votes

You probably already found a solution, but just in case it could be helpful for someone else, you could use this:

if(Ext.ClassManager.getAliasesByName('[Classname to check]').length > 0) {

    // create the requested component
    var component = Ext.create('[Classname to check]');

    // add replace the contents of the center container with the created component
    centerContainer.removeAll();
    centerContainer.add(component);

} else {
    console.log('Uknown component: '+ '[Classname to check]');
}

It will not give you an error and will not try to download your classfile, if it doesn't exist.

2
votes

In my case, the class I want to find didn't have an alias defined. I found that I could use this:

function createClassIfExists(name) {
    var newClass;

    if(!Ext.isEmpty(Ext.ClassManager.getNamesByExpression(name + '*')))
        newClass = Ext.create(name);

    return newClass;
}
0
votes
function openView(cid) {
    shortName = cid.substr(cid.lastIndexOf(".")+1, cid.length);
    if(Ext.get(shortName) == null) Ext.create(cid);
   Ext.Viewport.setActiveItem(Ext.getCmp(shortName));
}

This function opens a view like

openView('MyApp.view.Oeffnungszeiten');

and if the View exists it accesses the old instance

0
votes

If you are using the 'Ext.ClassManager' be aware of a caveat to finding if a Class exists or not. This code below will only work if your code has the Class you are looking for in the 'requires' section of the View code.

if(Ext.ClassManager.get('MyApp.view.Main'))

It will return undefined if it has not been added.

requires: [ 'MyApp.view.Main']

You can also add this to your App.js within the 'views' section too.