jquery - scrolly.js initializing code , a bit confusing -


i going through source code of simple parallax plugin, , came across piece of code seems very familiar or rather pattern across lot of other plugins ,

the plugin in concern :

scrolly.js

and bit of code thats confusing :

  $.fn[pluginname] = function ( options ) {         return this.each(function () {             if (!$.data(this, 'plugin_' + pluginname)) {                 $.data(this, 'plugin_' + pluginname, new plugin( this, options ));             }         }); 

somehow not able come terms piece of code.

on little enquiry, able demystify 1st line :

 $.fn[pluginname] = function ( options ) { 

what above line example:

assuming pluginname = "killtherabbit", same

 $.fn.killtherabbit = function ( options ) { 

but can call many times different values pluginname

i got following answer jquery forum .

i ran few debugging console.log statements , noticed function executes 1st when plugin called . perticularly don't understand below 2 lines @ .

if (!$.data(this, 'plugin_' + pluginname)) {             $.data(this, 'plugin_' + pluginname, new plugin( this, options ));         }  

i know data function in jquery @ play here , data function can used associate data element in dom , can later accessed (sorry if i'am wrong ! thats best understand doc's).

i particularly asking question because see snippet of code in lot of jquery plugins.

if choose answer question :

please elaborate possible , try explaining in simple english , less jquery terms possible .

also have supplementary question : there anyway can write test case show me function doing ?? , under circumstances if condition fails , passes ?? (you can choose not answer ! thats fine . ).

the following lines:

    if (!$.data(this, 'plugin_' + pluginname)) {         $.data(this, 'plugin_' + pluginname, new plugin( this, options ));     } 

are same pseudo code:

  if not elementdata["key"]        elementdata["key"] = new object   end if 

translated english as:

"if have not stored plugin object on element, using name of plugin key, then create instance of plugin , store instance on element, using name of plugin key".

this part creates javascript object instance, passing couple of useful parameters (javascript objects type of function):

new plugin( this, options ) 

test case supplementary question (just call twice on same element):

// first time go `if` , create object $('#elementid').killtherabbit();  // call again , not create object (as have plugin on element) $('#elementid').killtherabbit(); 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -