views:

47

answers:

1

I've been coding with jQuery for about 2 years now but I've never done it in a plugin. I'm trying to change this. I found a few websites that explain how to create a plugin and I understand the basics.

The part that I don't understand is the use of the this keyword. Here's a simple plugin example:

(function($){
  $.fn.myPlugin = function(options)
  {
    // Do whatever
    return this.each(function(){
      element = $(this);
    });
  }
  $.fn.myPlugin.init = function()
  {
    // Initiate plugin
  }
})(jQuery);

On the 5th line of my code, I have this.each. In this case, the this keyword refers to all the elements in the selector. The following line uses $(this) which is the current element, the same way as if I do it in a .click(function(){$(this).hide();}).

Now, in the OO logic, usually we have a this keyword to refer to internal functions or properties. If in $.fn.myPlugin I want to call $.fn.myPlugin.init(), I expected to be able to do with something like this.init() but it doesn't seem to be working.

Also, I was expecting to be able to define class properties in a similar way, something like this.myVariable = "my value".

So if anyone can explain whatever I'm missing to understand the plugin concept with jQuery, or point me in the right direction with a relevant link, I'd appreciate the help! If my explanations are not clear enough, let me know and I'll try to make it better, but it's kind of blurry in my mind right now. ;)

+1  A: 

Before you get into the .each(), this is actually the jQuery object that contains the set of matched DOM elements.

If you wanted to call that function in that manner, you would need to call it in the scope to which it was added. $.fn.myPlugin.

this.myPlugin.init();

or inside the each like this:

$(this).myPlugin.init();

Or directly like this:

$.fn.myPlugin.init();
patrick dw
this.myPlugin.init() and $.fn.myPlugin.init() both give me an undefined error...
Gabriel
@Gabriel - Depends where and when you're calling them. Try this example: http://jsfiddle.net/bRfdE/ You'll get 3 popups for the 3 different ways in which it is getting called. So the questions would be when/where are you calling it, and what does it do? You'll need to make a small change if you expect `this` to refer to the DOM element or jQuery object.
patrick dw
@patrick dw: you are absolutely right, sorry, my call was in an anonymous function in a bind(). This brings me another problem, but I'll figure something out I guess... Seems like all references to my ojects are lost when I'm in there...
Gabriel
@Gabriel - Yes, that's the tweak you'll need if you want to retain the expected value of `this`. Small change. Just do this instead: `this.myPlugin.init.call(this);` The `.call()` method lets you set the value of `this` for the function being called to whatever you want. So now in the `.init()` function, `this` will be whatever value you passed to `.call()`.
patrick dw