Tuesday, June 26, 2012

Example Wheel


Here's an example of a typical wheel i write these days:

/**
 * Copyright (c) 2012, Nathan Bubna
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * @version 0.1
 * @requires jQuery 1.7+
 * @optional roll.js
 */
;(function($, window, document) {

    var wheels = window.wheels = {
        init: function() {
            $('vehicle').each(function() {
                var vehicle = $(this);
                vehicle.trigger('addWheels', vehicle.attr('wheels'));
            });
        },
        add: function(e, count) {
            var vehicle = $(e.target).closest('vehicle');
            for (var i=0; i<count; i++) {
                wheels.attachOneTo(vehicle);
            }
            vehicle.trigger('addedWheels', [count]);
            if (!!vehicle.attr('roll')) {
                vehicle.trigger('roll');
            }
        },
        attachOneTo: function(vehicle) {
            // magic happens here
        }
    };

    $(document)
    .on('addWheels', wheels.add)
    .ready(wheels.init);

})(jQuery, window, document);

This is designed to be interacted with via events and DOM configuration.  It uses jQuery to fire and handle events as well as discover <vehicle> elements in the document.  It adds wheels according to the number specified in that element's "wheels" attribute:
<vehicle wheels="3" roll="true">some tricycle markup here</vehicle>
 It uses events to communicate what it is doing for others to listen and attach behaviors.  It even optionally fires a "roll" event once all the wheels are attached that is meant for a possibly non-existant "roll.js" to handle.

If a <vehicle> is added later, the user can give it wheels by simply firing an "addWheels" event on it.

The user of this "wheels.js" code can enjoy its benefits without ever directly accessing the window.wheels object, making his code both simpler and more robust.  But, if he wants to, he can use, override, or wrap any of the functions in wheels, as well as use them directly during a console debugging session.

No comments:

Post a Comment