简体   繁体   中英

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 :

  • the settings file must be loaded before the plugin. ( so the plugin will be able to read mySettings in the override settings area )

  • the only way to communicate mySettings with the plugin itself is via the window object

Question :

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

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'}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM