maxp
maxp

Reputation: 25161

Javascript / Jquery, instantiate multiple classes with similar global variables

I have a plugin i created which works great when there is only one instance of it on the page.

However it uses a global variable to store the current item index.

When I place multiple instances of this on the page, it all goes wrong, as each block of script gets confused because there are multiple instances of the same global variable on the page.

Is there any way i can 'instantiate' each plugin i add to the page to avoid this, so each block of javascript only accesses its own global fields / properties?

Upvotes: 1

Views: 490

Answers (1)

David Tang
David Tang

Reputation: 93694

You can attach the variable to the element using .data():

$(this).data('my-plugin', someValue);
// Note: if the above line is in a regular jQuery plugin ($.fn.myPlugin = ...)
// then 'this' does not need to be wrapped.

Retrieve it again with:

$(this).data('my-plugin');

This way the variable is associated directly with the element your plugin is initialised on.

Upvotes: 2

Related Questions