views:

59

answers:

2

I'm creating jQuery plugins using the pattern from the Plugins Authoring page:

(function($) {

   $.fn.myPlugin = function(settings) {
     var config = {'foo': 'bar'};

     if (settings) $.extend(config, settings);

     this.each(function() {
       // element-specific code here
     });

     return this;

   };

 })(jQuery);

My code calls for several private methods that manipulate this. I am calling these private methods using the apply(this, arguments) pattern. Is there a way of designing my plugin such that I don't have to call apply to pass this from method to method?

My modified plugin code looks roughly like this:

(function($) {

   $.fn.myPlugin = function(settings) {
     var config = {'foo': 'bar'};

     if (settings) $.extend(config, settings);

     this.each(function() {
       method1.apply(this);
     });

     return this;

   };

   function method1() {
     // do stuff with $(this)
     method2.apply(this);
   }

   function method2() {
     // do stuff with $(this), etc... 
   }

 })(jQuery);
A: 

Just create a scoped variable that points to this

(function($) {
   var me;
   $.fn.myPlugin = function(settings) {
     var config = {'foo': 'bar'};
     if (settings) $.extend(config, settings);
     me = this;
     this.each(method1);
     return this;
   };

   function method1() {
     // do stuff with me
     method2();
   }

   function method2() {
     // do stuff with me, etc... 
   }

 })(jQuery);
Sean Kinsey
You should use `me` in those methods, not `$(me)`, `this` is already a jQuery object, it's an unnecessary clone when re-wrapping it. I would have a read here for common mistakes like this: http://remysharp.com/2010/06/03/signs-of-a-poorly-written-jquery-plugin/
Nick Craver
I don't use jQuery myself, its a crappy library :) But I'll update the answer
Sean Kinsey
+3  A: 

I think jQuery.proxy was created for these problems, though in general it does similar to what you do:

this.each(jQuery.proxy(method1, this));
azatoth
Thanks for the response. The `jQuery.proxy` function is new to me. Isn't it simply syntactic sugar for `method1.apply()`?
thebossman
@thebossman - It's an `.apply()` internally: http://github.com/jquery/jquery/blob/master/src/core.js#L689
Nick Craver