Skip to content

Instantly share code, notes, and snippets.

@PetrKaleta
Created May 19, 2011 12:47
Show Gist options
  • Save PetrKaleta/980671 to your computer and use it in GitHub Desktop.
Save PetrKaleta/980671 to your computer and use it in GitHub Desktop.
jQuery plugin starter with methods support
(function($) {
$.fn.myPlugin = function(options, args){
this.each(function(){
$this = $(this);
var instance = $this.data('myPlugin');
if (instance && typeof(instance) == 'object')
callInstance(instance, options, args);
else
$this.data('myPlugin', new $.myPlugin(this, options));
});
function callInstance(instance, options, args){
if (options && typeof(options) == 'string')
switch(options){
case 'inspectOption':
instance.inspectOption(args);
break;
default:
throw 'Invalid method name';
}
else if (options && typeof(options) == 'object')
instance.updateOptions(options);
else
throw 'Invalid call';
}
return this;
};
$.myPlugin = function(img, options){
var options = $.extend({
opinion: 'This starter rocks!'
}, options);
this.updateOptions = function(opts){
options = $.extend(options, opts);
};
this.inspectOption = function(name){
console.log(name + ": " + options[name]);
};
};
})(jQuery);
$(document).ready(function(){
// initialize
$('#first').myPlugin();
$('#second').myPlugin({opinion: 'I love it!'});
// call method
$('#first').myPlugin('inspectOption', 'opinion'); // => opinion: This starter rocks!
$('#second').myPlugin('inspectOption', 'opinion'); // => opinion: I love it!
// update options
$('#first').myPlugin({opinion: 'Me too!'});
$('#first').myPlugin('inspectOption', 'opinion'); // => opinion: Me too!
});
@Inza
Copy link

Inza commented May 19, 2011

Very nice!:-)

@PetrKaleta
Copy link
Author

PetrKaleta commented May 19, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment