Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conflict between two jQuery plugins?

I'm developing a couple of jQuery plugins for a client website that will allow the styling of form elements such as radios, checkboxs and selects. I've been developing them as three separate plugins within the same file, and while the radio and checkbox plugins seem to work fine alongside each other, my select one is giving me trouble as it seems to stop the radio and checkbox from working! If I remove it the other two work fine again.

I presume I have some kind of conflict between them, but I am unsure as to where it could be. If I comment out all of the select plugin's code apart from its "settings" declaration the radio and checkbox are broken. If I remove the settings the radios and checkboxes start working again, so it seems the conflict is in the settings.

I have declared the plugin options the same in all three (just with their own defaults):

jQuery.fn.ioFormSelect = function(options) {
    //Default options.
    settings = jQuery.extend({
        'maxOptions': 8,
        'fieldClass': 'ui-field-select',
        'selectedClass': 'ui-field-selected',
        'openClass': 'ui-field-select-open',
        'closeClass': 'ui-field-select-close',
        'disabledClass': 'ui-field-disabled',
        'optionClass': 'ui-field-option',
        'optionGroupClass' : 'ui-field-option-group'
    }, options);

    //Plugin code

});

What am I doing wrong? I thought variables declared in this manner were "local" with "globals" being defined by the word "var" beforehand. Do I have to have a separate settings variable for each plugin? :S Many thanks in advance for any advice. :)

like image 247
Fourjays Avatar asked May 26 '26 03:05

Fourjays


1 Answers

You're missing a keyword here, var, like this:

var settings = jQuery.extend({

Without var, you're creating a global variable called settings, which of course will cause problems when more than one plugin tries to use it, when you don't intend to share it :)

For example you can test it like this:

​$("body").ioFormSelect();
alert(window.settings.maxOptions);​​​ //alerts "8"

There's a more detailed discussion on the topic in this question: Difference between using var and not using var in JavaScript

like image 186
Nick Craver Avatar answered May 27 '26 16:05

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!