Created
May 19, 2011 12:47
-
-
Save PetrKaleta/980671 to your computer and use it in GitHub Desktop.
jQuery plugin starter with methods support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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! | |
}); |
Glad you like it
…Sent from my iPhone 4
On 19.5.2011, at 20:19, ***@***.*** wrote:
Very nice!:-)
##
Reply to this email directly or view it on GitHub:
https://gist.github.com/980671
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice!:-)