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:
var ja = $('#jannounce').jannounce();
I then added the destroy method to the plugin and naturally called destroy on ja:
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:
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:
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:
ja.jannounce('destroy');