I’m rewriting a plugin so that each main section is turned into a method as per this question and the jQuery documentation, and so far the whole thing is still working.
The plugin is initialized with:
$('#mySelector').myPlugin({
// want to keep initial options
option1: true,
option2: 'right'
// etc.
});
Then later, I want to use a refresh method:
$('#mySelector').myPlugin('refresh');
Basically, I need “refresh” to do everything in this plugin, except re-applying the HTML DOM modifications (while keeping all of the original initialized options).
I can’t seem to figure it out. I cannot just use methods.binders(var1, var2); because I need to get the variables too. However, the init() needs the methods.html() when it’s first initialized. How can I skip that one part when I do my refresh?
Maybe it’s simple, but I have a headache now.
(function ($) {
var methods = {
defaults : {
option1: false,
option2: 'left'
// etc.
},
settings : {},
init : function(options) {
methods.settings = $.extend({}, methods.defaults, options);
$(this).each(function() {
if ($(this).is('[type=radio]')) {
var var1 = $(this);
var var2 = $('.somethingelse');
// etc.
methods.html(var1, var2);
methods.binders(var1, var2);
};
});
},
refresh : function () {
// no idea??
},
html : function(var1, var2) {
// various HTML DOM manipulations
},
binders : function(var1, var2) {
// binding various events, hover, click, etc.
// assigns classes
}
};
$.fn.myPlugin = 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 jQuery.myPlugin' );
}
};
})(jQuery);
Following moves most of the code from
methods.initto a functiondoInit()that can be called in bothmethods.initandmethods.refreshwith argument forinitTypeand a conditional inside to call some code forinitbut notrefreshMay not be bug free but idea should get you going
EDIT: Realized I forgot to make the settings more global. One way is to remove defaults from
methodsand createNow you have access to the user defined settings when you do the refresh. Another really helpful addition is to store the settings in jQuery DOM data like: