Lugo Labs

jQuery Plugin Methods

Yesterday I was in the middle of writing a jQuery plugin called jannounce. As I was writing some tests, I was pleased to acknowledge that I needed an external method called destroy. So I instantiated the plugin on a DOM element as a good jQuery programmer would do:

js
var ja = $('#jannounce').jannounce();

I then added the destroy method to the plugin and naturally called destroy on ja:

js
ja.destroy();

That's Object Oriented programming, right? But I got an error, saying that the destroy method doesn't exist; indeed, the destroy method was NOT added to the jQuery object, rather to the plugin function. Going through jQ docs, I found out the proper way to declare methods on a plugin (http://docs.jquery.com/Plugins/Authoring).

So I changed my plugin to do this. First I added the plugin object (with the destroy method in it) to the data of the DOM element; not the best way, I know, but ok for the moment:

js
var Announce = function (el) {
    el.data('ja-data', this);
};

Announce.prototype.destroy = function () {};

Now I can retrieve the plugin object from the jQ element and call its destroy function on the external destroy method:

js
var methods = {
    destroy: function () {
        var ja = this.data('ja-data');
        if (ja) ja.destroy();
    }
};

$.fn.jannounce = function(options) {
    // Method calling logic
    if ( methods[options] ) {
        return methods[ options ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof options === 'object' || ! options ) {
        return this.each(function () {
            var el = $(this);
            return new Announce(el);
        });
    } else {
        $.error( 'Method ' +  options + ' does not exist on jannounce' );
    }    
};

Now I can call my destroy method like this:

js
ja.jannounce('destroy');