Autoloading Element References with the DOM

It’s been a long time since I sat down and wrote anything about JavaScript; and with Dustin’s new book on design patterns in JavaScript, I felt that this would be a good time to post about a pattern that I’ve found myself using often.

You’d be hard pressed to find a JavaScript application that doesn’t manipulate the DOM nowadays. Usually there are a few elements that are manipulated often enough for them to be stored away in a property someplace for easy reference. If this sounds like any application you’ve written, you may like this.

Lets assume I have a registration form where users sign up for an account on a site:

MIKEG.widgetShop.registration = {
    'elements' : {
        'username'   : 'account-username',
        'password'   : 'account-password',
        'firstName'  : 'account-first-name',
        'lastName'   : 'account-last-name',
        'email'      : 'account-email',
        'messageBox' : 'system-messages'
    },

    'usernameExists' : function (sUserName) {
        // Code...
    },

    'validateData' : function () {
        // Code...
    },

    'renderMessage' : function (text, type) {
        // Code...
    }
};

The registration object stores an elements property which contains a set of property:value pairs which form the basis of this pattern. The property value contains the value of the ID attribute of the element we wish to reference.

When the DOM is in a usable state, you can safely load all of your element references into the elements property replacing the ID values with actual element references.

YAHOO.util.Event.onDOMReady(function () {
    var elements = MIKEG.widgetShop.registration.elements;

    for (i in elements) {
        elements[i] = YAHOO.util.Dom.get(elements[i]);
    }
});

And there you have it. Now anywhere inside the registration object you can simply address the element you want to target by this.elements.whatever. I’ve come to find that not only is this convenient, but it reads well and reduces code density substantially. Just look at how nice the implemented renderMessage method gets:

'renderMessage' : function (text, type) {
    this.messageBox.innerHTML = text;

    if (typeof type !== 'undefined') {
        YAHOO.util.Dom.addClass(this.messageBox, type);
    }
}

This entry was posted on Thursday, December 13th, 2007 at 3:14 am and is filed under Code, Design Patterns, JavaScript. You can leave a response, or trackback from your own site.

What do you have to say?

Site Stuff

Pages

Projects

Archives

Categories