I am want to build a plugin with accessible methods and options, this for a complex plugin.
I need the methods to be accessible outside the plugin because if somebody ads something to the DOM it needs to be updated(so we dont need the run the complete plugin again).
I have seen in the past that there are plugin that do it like this, but I cant find them, so I cant take a look at them. I am still new to javascript so any help would be nice.
It would be nice if we still can globally override the options.
How I want to use the plugin:
// options
$('#someid').myplugin({name: 'hello world'});
// methods(would be nice if we can use this)
$('#someid').myplugin('update');
// my old plugin wrapper
;(function($, window, document, undefined){
$.fn.pluginmyPlugin = function(options) {
options = $.extend({}, $.fn.pluginmyPlugin.options, options);
return this.each(function() {
var obj = $(this);
// the code
});
};
/**
* Default settings(dont change).
* You can globally override these options
* by using $.fn.pluginName.key = 'value';
**/
$.fn.pluginmyPlugin.options = {
name: '',
...
};
})(jQuery, window, document);
Update
So after looking at the jQuery docs I have build the following code, please let me know if there’s something wrong with the code, if it can be build better…
;(function($, window, document, undefined){
var methods = {
init : function( options ) {
options = $.extend({}, $.fn.pluginmyPlugin.options, options);
return this.each(function(){
alert('yes i am the main code')
});
},
update : function( ) {
alert('updated')
}
};
$.fn.pluginmyPlugin = function(method) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on this plugin' );
}
};
/**
* Default settings(dont change).
* You can globally override these options
* by using $.fn.pluginName.key = 'value';
**/
$.fn.pluginmyPlugin.options = {
name: 'john doe',
//....
};
})(jQuery, window, document);
An alternative:
Usage:
This absurdly resembles the Twitter Bootstrap’s JavaScript template. But, it wasn’t completely taking from there. I have a long history of using
.data().Don’t forget to wrap it appropriately.