Royi Namir
Royi Namir

Reputation: 148524

Override settings of jQuery plugin?

I've built a plugin like this :

;(function ($,window,undefined){

  ...
  ...default settings area...
  ...content area...
  ...

})(jQuery,window);

But this plugin can have many(!) configurations .(files configurations)

So each configuration file can be in a js file . example :

mySettings.js :

var mySetings= {a:1,b:2.....}

So where is the problem :

Question :

What is the correct way to configure a plugin which can have many(!) settings via js file.

Upvotes: 0

Views: 235

Answers (1)

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

As I don't have a code example to work with I'll give you some generalized solutions.

  1. Collect the settings object(s) in an array and iterate over them within your override settings area.
  2. Expose your plugin via window and directly append the settings there.

Example 1

JS

//File 1.js
window.settings = window.settings || []; 
window.settings.push({a:'11'}); 

//File2.js
window.settings = window.settings || []; 
window.settings.push({b:'22', c:'33'}); 

//File3.js
window.settings = window.settings || []; 
window.settings.push({b:'222'}); 

//Main.js File
;(function ($,window,undefined){

    var plugin = function(settings){
        var defConfig = {
            a: '1', 
            b: '2',
            c: '3'
        }; 

        var len = settings.length, i; 

        if(len){
            for(i = 0; i < len; i++){
               defConfig = $.extend(defConfig, settings[i]); 
            }
        }else{
            defConfig = $.extend(defConfig, settings); 
        }

        alert(JSON.stringify(defConfig)); 
    }; 

    var instance = new plugin(window.settings || []); 

})(jQuery,window);

Example 2

//Main.js File
;(function ($,window,undefined){

    var plugin = function(){
        var defConfig = {
            a: '1', 
            b: '2',
            c: '3'
        }; 

        this.overrideSettings = function(settings){
            var len = settings.length, i; 

            if(len){
                for(i = 0; i < len; i++){
                   defConfig = $.extend(defConfig, settings[i]); 
                }
            }else{
                defConfig = $.extend(defConfig, settings); 
            }

            alert(JSON.stringify(defConfig)); 
        }
    }; 

    window.instance = new plugin(); 

})(jQuery,window);


//File 1.js
window.instance.overrideSettings({d:'93'}); 

//File2.js
window.instance.overrideSettings({b:'22222'}); 

Upvotes: 2

Related Questions