How do I prevent multiple inits of a widget in jquery?
Lets say I have a jquery plugin called widget which can be used on multiple elements
e.g. $('.myClass').widget();
After the page has loaded I am dynamically adding HTML which contains more elements that have the class 开发者_运维百科myClass
. If I run the code above again, the previously loaded widgets will get initialized again.
One solution I came up with is to remove the class myClass
after the widget is initialized.
Another idea is to use .data()
and store an init flag check if it exists when the plugin loads.
Is there a better way of doing this?
I'd say just add on a new class when it's initialized and use the not
selector to exclude elements that have that class.
//Only will work once per element, no matter how many times you run it.
$('.myClass').not('.initialized').widget().addClass('initialized');
$(".myClass-init").widget().removeClass(".myClass-init")
Add a new class called myClass-init
This means you can continue using myClass
for CSS styling and are using a separate new class merely for functionality.
You could use data-
attributes but the selectors for those are slower. That's a question of whether you think data-
attributes are more semantic then an extra class
The jQueryUI widget framework generates pseudo selectors, so if your widget is named 'myWidget' you may use this line to test if it has been initialized:
$("#element").is(":ui-myWidget")
精彩评论