Static variables - jQuery plugins; how to create?

What is the best way to create static variables for jQuery plugins?

I have two examples of use to illustrate my thinking; each with some ideas.
Of course, any other ideas are welcome ...

One example is a static variable containing: animation settings, layout settings, product details, etc .; another for static data caching variables.

Hopefully “static” is the correct terminology here ... single globals. correct if you are mistaken.

Case 1: for settings

// defining globally
var anObject = {
 value1 = 0;
 value2 = 0;
}

jQuery.anObjectSet(partialObject) {
 anObject = jQuery.extend(anObject, partialObject);
}

jQuery.fn.myPlugin = function (partialObject) {
 obj = jQuery.extend(anObject, partialObject);
}

or maybe?

// adding to the jQuery object
jQuery.anObject = {
 value1 = 0;
 value2 = 0;
}

jQuery.anObjectSet(partialObject) {
 jQuery.anObject = jQuery.extend(jQuery.anObject, partialObject);
}

jQuery.fn.myPlugin = function (partialObject) {
 obj = jQuery.extend(jQuery.anObject, partialObject);
}

or maybe?

jQuery.anObjectSet(partialObject) {
 if(!jQuery.anObject) 
  jQuery.anObject = {
    value1 = 0;
    value2 = 0;
  }

 jQuery.anObject = jQuery.extend(jQuery.anObject, partialObject);
}

jQuery.fn.myPlugin = function (partialObject) {
 if(!jQuery.anObject) 
  jQuery.anObject = {
    value1 = 0;
    value2 = 0;
  }
 obj = jQuery.extend(jQuery.anObject, partialObject);
}

Case 2: for caching

jQuery.fn.myPlugin = function (newObject) {
 if(!cache[newObject])
  cache[newObject] = $(newObject);

 return cache[newObject];
}

or maybe? (I saw this method elsewhere)

window.$cache = {};

jQuery.fn.myPlugin = function (newObject) {
 if(!$cache[newObject])
  $cache[newObject] = $(newObject);

 return $cache[newObject];
}

Thank. I want to create a .js library starting from the right path ...

+5
1

"" , - .

- , , , .

, , "" . , , .

(function($){
    var $cache = {};

    jQuery.fn.myPlugin = function (newObject) {
      if(!$cache[newObject])
        $cache[newObject] = $(newObject);

      return $cache[newObject];
    }

})(jQuery);

Edit:

$cache , . , , .

(AFAIK) , , , $cache.

, . , , .

+11

All Articles