Reputation: 5974
I was just asking myself what happens if a plugin is applied more than once to an element
Suppose I do $("#my_element").plugin();
and then somehow I do exactly the same thing $("#my_element").plugin();
I'm sorry if this question doesn't belong here. Tell me so and I will delete it.
Upvotes: 0
Views: 194
Reputation: 22570
It's all at the discretion of the plugin writer. There is no "real" way for jQuery to say "Hey, don't do that!" However, a good plugin writer will usually have an "initialization" method that may assign a class or data variable to the original element the plugin was called on. Something like:
/* Example Plug-in Setup */
(function($) {
if (!$.myExample) {
$.extend({
myExample: function(elm, command, args) {
return elm.each(function(index){
// here a check is made to see if this plugin has touched this element before
if (!$(this).hasClass('my-example')) {
$.myExample.init.apply($(this), arguments);
}
else {
// do work to each element as its passed through
}
});
}
});
$.fn.extend({
myExample: function(command) {
return $.myExample($(this), command, Array.prototype.slice.call(arguments, 1));
}
});
$.myExample.init = function() {
// here we initialize the plugin on this element for the first time
// Assign element the class stating "hey, you've been here!"
this.addClass('my-example');
};
}
})(jQuery);
Keep in mind this is just one example and there are many different ways to design a plugin based on different needs, but this should give you a base idea of how a plugin "checks itself" before it "wrecks itself"!
"Do you know what could happen if that check isn't present?"
Well, that is a "loaded question". It really depends on "what" the plugin was written to do. Many different things could happen.
For instance, if you wrote a plugin to clone a form and hide a copy on the DOM, then every time you called the plugin on that form, a new copy would be saved to the DOM! This could be horrendous if the purpose was to withhold specific info for a database upload.
Then again, it could simply be a plugin that rewrites the "inner" HTML of an element, thus it would just be rewritten when called again and may appear to have no effect at all.
Simply put, whatever happens is up to the Plugin Writer, but don't view plugins as a "foreign object". They are just JavaScript, in this case using jQuery, wrapped in a file and/or plugin method. This doesn't help them supersede anything you already see in JavaScript code. It simply means "extending" a library. Thus giving you "pre-written" code that you would otherwise need to write yourself.
Upvotes: 2