2

I am using this set-up to allow accessing the variable outside the jQuery plugin:

(function($){

  $.fn.myplugin = function() {
    return this.each(function() {
      // plugin code here
      console.log($.fn.myplugin.myvar);
    });
  };

  $.fn.myplugin.myvar = { ... };

})(jQuery);

I can access myvar inside and outside the plugin using $.fn.myplugin.myvar. But it's quite verbose... I feel like there must be a way to access the variable inside the plugin with a shorter name, like this.myvar. That example doesn't work as this refers to the current element. But is there another way to access the variable more simply?

DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290

3 Answers3

3

$.fn is an alias to the jQuery's prototype, so I don't think there is a simpler way, unless you save that plugin in a variable.

What does jQuery.fn mean?

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 1
    Yes, after declaring the plugin function you could assign it to a variable like `exports`, for example, following the CommonJS convention: `var exports = $.fn.myplugin; exports.myvar = ...` – Matt Browne Feb 24 '13 at 20:46
1

gdoron's answer is the simplest solution...another thing you could consider would be writing your plugin in an object-oriented style, e.g.

function MyPlugin(element) {
    this.element = element;
}

MyPlugin.prototype.init = function() {
    //plugin code here
}

MyPlugin.myVar = { ... };

$.fn.myplugin = function() {
    return this.each(function() {
        var instance = $(this).data('myplugin');
        if (!instance) {
            var instance = new MyPlugin(this);
            $(this).data('myplugin', instance);
        }
        instance.init.apply(instance, arguments);
    });
}

Then if you needed to access any of the instance properties or methods, you could do so via $('#someElement').data('myplugin');. You could also make the same methods available by letting the first parameter be the method name, followed by the method arguments, like how jQuery UI works...but that gets slightly more complicated to implement. If you're interested, Google "jQuery widget pattern."

Matt Browne
  • 12,169
  • 4
  • 59
  • 75
  • Note that if `myVar` were instance specific, it should be declared within the `MyPlugin` constructor, e.g. `this.myVar = {...}` – Matt Browne Feb 24 '13 at 20:57
0

I think it'd just be easier to assign the variable when you define the function (demo):

var myplugin;
(function($){

  myplugin = $.fn.myplugin = function() {
    return this.each(function() {
      // plugin code here
      console.log(myplugin.myvar);
    });
  };

  myplugin.myvar = { test: true };

})(jQuery);
Mottie
  • 84,355
  • 30
  • 126
  • 241