Search code examples
javascriptextjsobserver-patternlistenersobservable

ExtJS 4 get every listeners of an observable object


I've an observable object defined as follows:

Ext.define ('MyObject', {
  mixins: {
    observable: 'Ext.util.Observable'
  } ,
  constructor: function (cfg) {
    this.initConfig (cfg);
    this.mixins.observable.constructor.call (this, cfg);
    ...
  }
});

Then, I create an instance of this object and attach some listeners:

var obj = Ext.create ('MyObject', {...});
obj.on ({
  first: function () {...} ,
  second: function () {...} ,
  third: function () {...} ,
  fourth: function () {...}
});

In the end, I'm gonna destroy the 'obj' instance, but at this point I've to save every listeners previously attached because I'm mad and I need to create another instance of 'MyObject', with the same configuration of 'obj', listeners included.

So, the question is: how can I save every listener of an observable object?

Thank you so much!


Solution

  • You can try create a getListeners() method for your object:

    Ext.define ('MyObject', {
    
        ...
    
        getListeners: function() {
            var me = this,
                l = {};
            for(var event in me.hasListeners) {
                Ext.each(me.events[event].listeners, function(listener) {
                    l[event] = listener.o[event];
                });
            }
            return l;
        }
    });
    
    ...
    
    var listeners = obj.getListeners();
    obj.destroy();
    
    obj2.on(listeners);
    

    See on jsfiddle: http://jsfiddle.net/8GMsp/

    Note: I have not tried to use it in a real application. May be require revision.