0

I want to create a utility class which can have just one instance(singleton) therefore I have made a static method called getInstance() which would create a instance and return it to me.

I have posted below the code with a comment where i get and error and the the error description. Please let me know whats wrong with the code.

Any help appreciated.

Ext.define('MyApp.utility.EventManager',{
    extend:'Ext.util.Observable',
    instance: new MyApp.utility.EventManager(), //error as undefined EventManager property  
    statics:{
          // instance: new MyApp.utility.EventManager(),
        getInstance:function(){
            if(!this.self.instance){
                this.self.instance=Ext.create('MyApp.utility.EventManager');
                return this.self.instance;
            }
            else{
                return this.self.instance;
            }
        },

    },

    constructor:function(){
        this.addEvents(
            'success'
        );
    },

});
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121

1 Answers1

1

It is obvious, that your get an error in new MyApp.utility.EventManager() when you are using it in the definition of the class. At the time you define the class, it does not yet exist, and therefore you cannot instatiate it with new.

The solution is easy, since a singleton class is already a feature of the Ext framework. Define your class using the built-in singleton-config.

Ext.define('MyApp.utility.EventManager',{
    extend:'Ext.util.Observable',
    singleton: true,   
    constructor:function(){
        this.addEvents(
            'success'
        );
    },
});

You do not need a getInstance method, because the Object MyApp.utility.EventManager is always the instatiated singleton.

Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
  • Yes Lorenz I knew about singleton feature but the problem is i want to add listener for events in another class for which I would require an instance of my class how would I do that? What i intended to was something like this. `var instance=MyApp.utility.EventManager.getInstance();` `instance.on('success',someFunction());` – Abhijeet Sonawane Jan 19 '14 at 14:53
  • I'm not sure if I understand, but instead of `var instance=MyApp.utility.EventManager.getInstance(); instance.on('success',someFunction());`, you could just write `MyApp.utility.EventManager.on('success',someFunction());` – Lorenz Meyer Jan 19 '14 at 14:57