May 26th, 2010 by radu

I like ExtJs and the way it is so modular. This time I needed to have something very easy, which is not implemented by default in Ext, so I rolled my own. I needed windows to fire ‘tofront’ and ‘toback’ events. In an app I am working on, the user can have quite many windows opened and I needed to know programatically when a window comes to front (and to back). The approach was to override the toFront method in Ext.Window. Below you can see the code, with some basic comments.

NOTE: I know there are the activate and deactivate events on every window, but when a window triggers the ‘deactivate’ event, Ext.WindowMgr.getActive() still returns it as the active window. This is why I needed the ‘tofront’ and ‘toback’ events.

(function(){

    // get the previous implementation of the toFront method
    var prevToFront = Ext.Window.prototype.toFront;

    Ext.override(Ext.Window, {

        toFront: function(){

            //get the window manager of this window, or Ext.WindowMgr if it doesn't have one
            var manager = (this.manager || Ext.WindowMgr);
            //get the window which is currently to front
            var activeWindow = manager.getActive();

            prevToFront.apply(this, arguments);

            //only fire tofront and toback events if the current window was not already to front
            if (this != activeWindow){
                this.fireEvent('tofront');
            }

            if (activeWindow){
                activeWindow.fireEvent('toback');
            }

            return this;
        }

    });
})();

I needed to run code both before and after the default implementation of the toFront method. If I didn’t need this, an easier approach would have been to use createSequence:

Ext.override(Ext.Window,{
       toFront: Ext.Window.prototype.toFront.createSequence(function(){
             // code here.
       })
})

Nice ExtJs! Go try it!

Leave a Reply