2

Basically, I'm using an existing jQuery plugin that I want to have 2 instances available to use from Jquery.

So for this html:

<div id="div_1"></div>
<div id="div_2"></div>

I would be able to do this:

$('#div_1').myplugin();
$('#div_2').copy_of_myplugin();

Now myplugin is being loaded by a script I pull in from an external source at the top of my html file.

If I console.log($()); I can see a list of all the native jQuery methods as well as the one added by the plugin script.

Basically, after a bit of research I think something like this should work, but I can't work out exactly how to do it.

$.fn.copy_of_my_plugin = function () {
    return this.each(function () {
        var instance = $(this);
        if (instance.data('copy_of_my_plugin')) {
            return;
        }
        var copy_of_my_plugin = new $.extend(true, {}, $.fn.myplugin);
        instance.data('copy_of_my_plugin', copy_of_my_plugin);
    });
};

I can console.log($()); again and see that copy_of_my_plugin is being added to jquery, but it looks like none of the contents of the myplugin function are actually being copied.

Anyone have any idea what I'm doing wrong?

Rooster
  • 9,954
  • 8
  • 44
  • 71

1 Answers1

1

It's quite difficult to figure out what you are trying to do in your code. You do realise that your variable "instance" is actually being set to the dom element id="div_2" in your example. Are you trying to get 2 instances of the same plugin or are you just trying to get the same functionality with 2 plugin names? Are you sure you are not just trying to do this?

$.fn.a_copy_of_my_plugin = $.fn.myplugin;

If you take your code, when you do a console.log() & are able to "see your plugin" - it is not actually a copy of anything it is just a pointer to the function you are assigning to $.fn.copy_of_my_plugin in your code above. Only when you do $('#div_2').copy_of_myplugin(); is it then running that function which tries to "create the second instance" so to speak.

If you wanted to run the function immediately you would replace }; with }($); as your very last line of code.

As your code stands the this.each only runs when you use $('#div_2').copy_of_myplugin(); and then tries to store a copy of a new object in jQuery's data cache for $('#div_2').

You might want to take a look at this. I think it should do what you are after Best Way to Extend a jQuery Plugin

Community
  • 1
  • 1
Precastic
  • 3,742
  • 1
  • 24
  • 29
  • AFter reading the link and digesting your comments, this indeed led me to the proper answer. I was copying a pointer to the original function instead of copying the object that created the plugin. I got there with MyPLuginCopy = new $.extend(true, {}, window.MyPlugin); and then accessing its methods. – Rooster Jun 14 '13 at 18:59