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. ;)