qinHaiXiang
qinHaiXiang

Reputation: 6419

Is it possible to make several jquery plugins to share the same variable?

I asked a question how to get another plugin's variable before , but I thought it was not the right way to resolve my problem.So,I think the best way maybe to share the same variable. E.g:

I have a global variable zIndex , and each time my plugin [ may be plugin1,plugin2...] create a new element it gets the z-index value from it and plus one and assign back to zIndex , and every time the element which was click, the element get the latest zIndex value and plus one and return it to zIndex.

So,every new created elements could get the latest zIndex value,and every time the element was clicked,it get the latest zIndex and update the zIndex value.

and the question is: Is it possible to share this kind of global variable among plugins and how could I update the global variable inside the plugin??

Thank you very much!!

Upvotes: 2

Views: 188

Answers (1)

jAndy
jAndy

Reputation: 235982

If you have full control over your plugins, you can just use a simple Closure to share variables:

(function($) {
     var mySharedVariable = "shared";

     $.extend($.fn, {
         plugin1:  function() {
            return this.each(function(i,e) {
                mySharedVariable = "plugin1";
            });
         },
         plugin2:  function() {
            return this.each(function(i,e) {
                mySharedVariable = "plugin2";
            });
         }
     });
}(jQuery));

Since the functions plugin1 and plugin2 have the same parent scope (or more precisely, their Activation-Object), they will share the access to mySharedVariable.

Demo: http://www.jsfiddle.net/EMpQN/

Upvotes: 1

Related Questions