I am trying to make a parallax plugin for myself and found a simple parallax plugin online called scroll.js :
it has a few confusing lines of code though, even multiple checks to the doc's don't help. The jQuery documentation says that the data method in jQuery accepts a key : Value
pair and even though a lot of code in the plugin is passed through reference, I don't see a key:value pair formation.
A Google search does slightly better and I had an overall better understanding of the data
method after a search on Google, however that still did't help me in the context of using the data
method in jQuery plugins, so here's my difficulty.
the snippet of code that I did't understand is :
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
};
the entire plugin source code can be found here (don't worry ! its just under 100 lines ! not a huge plugin) . Plugin on Git
Now my difficulty with the above piece of code is, all the examples of the data method I have seen so far in tutorial etc, the usage of the data
method in the real world plugin is rather different. What is the author really using the data function here for?
Apart from the line:
return this.each(function () {
all other lines of code, i don't totally confidently understand them. what are they doing?
eg. what is the below line doing ?
if (!$.data(this, 'plugin_' + pluginName)) {
checking if 'plugin_' + pluginName has an properties initailized as an object literal ?? is my assumption correct?
what if the condition returns true? :
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
the above line of code is executed, but what is it doing again ??
I see the data method being used again, the keyword this is used to point to the current element, 'plugin_' + pluginname (i guess this specifies that "this" should point 'plugin_' + pluginname??? ) and lastly a new instance is created.
My understanding of Jquery is not great, I have made an attempt to guess or rather interpret what's happening in this small snippet of code. Sorry if my interpretation is way off the mark.
If somebody could really come along and tell me whats really happening, that would be great.
An important reason for me asking this question is because i have seen similar snippets of code in a lot of contemporary Jquery plugins .