Multi Instance Plugin Issue
Hey all,
I'm in the process of writing a JQuery Plugin, and have ran into a bit of a snag. When I create multiple instances of a plugin, it always ends up returning the last instance that was created.
Can any of you JQuery wizards help me out?
Here is an example of the code that I'm using. I'm currently testing this in chrome.
- <html>
- <title>Sample</title>
- <head>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
- <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.23/jquery-ui.min.js"></script>
- <script language="javascript" type="text/javascript">
- $(document).ready(function () {
- $('#hello').samplePlugin('Hello Plugin');
- $('#by').samplePlugin('By Plugin');
- $('#clickme').click(function () {
- $('#hello').DisplayShowTitle();
- $('#by').DisplayShowTitle();
- });
- });
- (function ($) {
- $.samplePlugin = function (el, title, options) {
- // To avoid scope issues, use 'base' instead of 'this'
- // to reference this class from internal events and functions.
- var base = this;
- // Access to jQuery and DOM versions of element
- base.$el = $(el);
- base.el = el;
- // Add a reverse reference to the DOM object
- base.$el.data("samplePlugin", base);
- base.init = function () {
- if (typeof (title) === "undefined" || title === null) title = "null";
- base.title = title;
- base.options = $.extend({}, $.samplePlugin.defaultOptions, options);
- // Put your initialization code here
- };
- // Sample Function, Uncomment to use
- base.showTitle = function (paramaters) {
- return base.title;
- };
- // Run initializer
- base.init();
- $.fn.DisplayShowTitle = function () {
- var message = base.showTitle();
- alert(message);
- return message;
- };
- };
- $.samplePlugin.defaultOptions = {
- };
- $.fn.samplePlugin = function (title, options) {
- return this.each(function () {
- (new $.samplePlugin(this, title, options));
- });
- };
- })(jQuery);
- </script>
- </head>
- <body>
- <div id="hello" name="hello">
- Hello</div>
- <div id="by" name="by">
- By</div>
- <input id="clickme" name="clickme" type="button" value="click" />
- </body>
- </html>
Thanks for any help