Instance-aware plugins take things to the next level in terms of usability. jQuery UI does this in all of thier plugins.
For example, jQuery UI can create a dialog, then call it again. That is what "instance-aware" means:
<script>
jQuery('.mydialog').dialog({ autoOpen : false });
jQuery('.mydialog').dialog('open');
</script>
So here is how to do that and I've tried to keep it as small and simple as possible with comments to help you out
<script>
$.fn.myPlugin = function() {
var $self = $(this),
args = Array.prototype.slice.apply(arguments),
config = {
someValue : 'default value'
},
instanceMethods = {
method1 : function() {
alert(config.someValue);
},
method2(self, anotherValue) {
alert(config.someValue + ' ' + anotherValue);
}
};
if ($self.data('myplugin-defined')) {
config = $self.data('myplugin-config');
if (args.length > 0) {
instanceMethods[args[0]].apply(this,args.slice(1,args.length));
}
return $self;
} else {
$self.data('myplugin-defined', true);
if (args.length > 0 && $.isPlainObject(args[0])) {
config = $.extend(config, args[0]);
}
$self.data('myplugin-config',config);
}
return $self;
};
</script>
Since I didn't find any books on this subject or resources online, thought this could help.
Contact for bugs, etc.