PLUGIN EXAMPLE - A simple data access layer for jQuery plugins

This is an extremely simple way of accessing data via a jQuery plugin dynamically, it makes use of the jQuery.data method and updates on each index value change

by bizamajig

CSS

body {
    font: 12px/16px sans-serif;
    margin: 10px;
}

span {
    background-color: #eee;
    border-radius: 5px;
    display: block;
    margin-bottom: 10px;
    padding: 5px 10px;
}

strong {
    font-weight: bold;
}

JavaScript

(function($) {
    $.fn.dataTest = function(options) {
        // Set the default options
        var defaults = {
            foo : 'true',
            bar : 'false'
        };
        
        // Merge the user defined options with the default options
        options = $.extend(defaults, options);
        
        // Construct a data object that can be called via the jQuery.data method
        var dataFn = {
            opts : options,
            
            // Sets the defined option value if it exists
            set  : function(name, value) {
                if (this.opts[name]) {
                    this.opts[name] = value;
                }
                
                // Update the data object for the element
                this.$el.data('dataTest', this);
                
                // Return the current object which creates method chaining and cleaner code
                return this;
            },
            
            // Retrieves the value for the defined option
            get : function(name) {
                return this.opts[name] || null;
            }
        };
        
        // Loop through each element in the DOM selection
        return this.each(function() {
            // Store the element object in the dataFn object
            dataFn.$el = $(this);
            
            // Bind the dataFn object to the element
            $(this).data('dataTest', dataFn);
        });
    };
})(jQuery);

// Construct the plugin instance for the DOM selection
var dt = $(document).dataTest().data('dataTest');

// Update the values for "foo" and "bar"
dt.set('foo', 'false').set('bar', 'true');

// Update the values for "foo" and "bar"
setTimeout(function() {
    dt.set('foo', '3 seconds').set('bar', 'later...');
}, 3000);

// Update the values for "foo" and "bar"
setTimeout(function() {
    dt.set('foo', 'Back to normal').set('bar', 'in 3 more seconds...');
}, 5000);

// Update the values for "foo" and "bar"
setTimeout(function() {
   ...