kboom
kboom

Reputation: 2339

jQuery plugin object looses variable?

I'm developing a simple plugin with jQuery. As I see it I need to do it like this:

(function($) {

   var somePrivateFn = function() {
       alert(this.x);
   }

   $.fn.myPlugin = function() {

       if(typeof arguments[0] === "string") {
            var fnargs = Array.prototype.slice(arguments, 1);
            // pluginData will be undefined
            var pluginData = this.pluginData;
            somePrivateFn.apply(pluginData, fnargs);
       }

       return this.each(function() {
           var data = this.pluginData = {};
           data.x = 1;
       };
   }
})(jQuery);

Of course my plugin needs to store some variables for the jquery object it's working on. To do this I just place an additional variable "pluginData" at the jQuery object itself. The problem is it is not accessible later. How to deal with it? What's the best approach to do this?

Upvotes: 0

Views: 32

Answers (1)

Popnoodles
Popnoodles

Reputation: 28409

Pass the object when you run the plugin. $('div').myPlugin(a_data_object) It will persist to within the this.each loop.

This var options=$.extend({}, pluginData); will keep the data in one iteration from passing through to the next.

If you want to manipulate then store that data on the element you would use $.data().

(function($) {
   console.clear();
   var somePrivateFn = function(data) {
       console.log(data.x);
   }

   $.fn.myPlugin = function(pluginData) {
       // send to another func
       somePrivateFn(pluginData);
       // use on each div
       return this.each(function(i) {
           var options=$.extend({}, pluginData);
           // add some example data
           options.y = "i am y";
           options.iteration=i;
           options.text=$(this).text();
           // store it on the element   
           $(this).data('pluginData', options);
       });      
   }

   // run the plugin on div elements
   $('div').myPlugin({x:"i am x"});

   // check out the data later
   $('div').each(function(){
        console.log($(this).data('pluginData'));
   });

})(jQuery);

Example: http://jsfiddle.net/xXt5W/1/
$.data() docs: https://api.jquery.com/jQuery.data/

Upvotes: 1

Related Questions