Friday, January 18, 2008

A client-side component for managing window resize events

I wrote a while back about fixing IE's window resize event, and while this implementation works well, it was difficult for other components to hook into and use without re-writing the same code.

I decided to write a client-side component that handles the window resize event and fires off its own event when the resize has actually completed.

The code is pretty much the same as my original post, except its encapsulated in a MS AJAX component and exposes a new event.

The JavaScript looks like:

/// <reference name="MicrosoftAjax.js" />

Type.registerNamespace('Mbccs.Psp.Web.Manager');

Mbccs.Psp.Web.Manager.WindowHelper = function() {
    Mbccs.Psp.Web.Manager.WindowHelper.initializeBase(this);   
    this._resizeTimeoutHandle = null;
    this._resizeEventDelegate = null;
    this._resizeHandlerDelegate = null;
}

Mbccs.Psp.Web.Manager.WindowHelper.prototype = {   
    initialize : function() {           
        Mbccs.Psp.Web.Manager.WindowHelper.callBaseMethod(this, 'initialize');
        if(this._resizeEventDelegate === null)
            this._resizeEventDelegate = Function.createDelegate(this, this._resizeHandler);
        if(this._resizeHandlerDelegate === null)
            this._resizeHandlerDelegate = Function.createDelegate(this, this._resizedHandler);
        $addHandler(window, 'resize', this._resizeEventDelegate);
    },

    dispose : function() {       
        if(this._resizeEventDelegate) {
            $removeHandler(window, 'resize', this._resizeEventDelegate);
            delete this._resizeDelegate;
        }
        if(this._resizeHandlerDelegate)
            delete this._resizeHandlerDelegate;
        Mbccs.Psp.Web.Manager.WindowHelper.callBaseMethod(this, 'dispose');
    },
    _resizeHandler : function(e) {
        window.clearTimeout(this._resizeTimeoutHandle);
        this._resizeTimeoutHandle = window.setTimeout(this._resizeHandlerDelegate, 100);       
    },
    _resizedHandler : function(e) {
        this._onWindowResized(Sys.EventArgs.Empty);
    },
    //
    // Events
    //
    add_windowResized : function(handler) {
        this.get_events().addHandler('windowResized', handler);
    },
    remove_windowResized : function(handler) {
        this.get_events().removeHandler('windowResized', handler);
    },
    _onWindowResized : function(e) {
        var h = this.get_events().getHandler('windowResized');
        if(h) h(this, e);
    }
}

Mbccs.Psp.Web.Manager.WindowHelper.registerClass('Mbccs.Psp.Web.Manager.WindowHelper', Sys.Component);

An example of using it on your site:

Sys.Application.add_init(function() {                 
       window.windowManager = $create(Mbccs.Psp.Web.Manager.WindowHelper, null, {windowResized : page_windowResized}, null, null);
});

function page_windowResized(sender, args) {
    alert('Window has been resized!')
}

No comments: