2016-10-13 83 views
-1

這是到目前爲止我的jQuery插件參數:jQuery的延長()在延長()

function lightbox(options) 
{ 
// setting default parameters 
var params = $.extend(
{ 

    // show/hide & enable/disable options 
    keyNav : true,      // boolean 
    objClickNav: false,     // boolean 
    showNav : true,      // boolean 
    showTitle : true,     // boolean 
    showPagination : true,    // boolean 
    debugMode : false,     // boolean 
    disableScrolling : true,   // boolean 
    fullscreen : false,     // boolean 

    autoScale : true,     // boolean 
    staticHeight: 'auto',    // integer or 'auto' 
    staticWidth: 'auto',    // integer or 'auto' 

    // content options 
    contentType : 'image',    // defines the type of content shown in the lightbox 
             // options: 'image' 
    animationType : 'default',   // defines the type of animation when switching objects 
             // options: 'default', 'slide' 

}, options); 
} 

我不能在互聯網上的任何地方找到答案,所以這就是爲什麼我要問在這裏。我想有當前extend()內的extend(),這樣我就可以宣佈我的插件是這樣的:

lightbox({ 
    keyNav : true, 
    showNav : false, 
    scale({ 
    autoScale : false, 
    staticHeight : 800, 
    }) 
    content({ 
    contentType : 'image', 
    animationType : 'slide', 
    }) 
}); 

什麼是這樣做的正確方法是什麼?

+1

你應該要創建一個與傳入插件的設置具有相同結構的默認設置對象,那麼您可以只用'.extend'。你現在所擁有的是一個扁平的對象作爲默認對象,然後突然傳入一個嵌套對象,你將會遇到很多迭代的麻煩,並且弄清楚什麼地方會發生什麼,而不是僅僅把它們變成同樣的結構首先。 – adeneo

+0

也許你可以用一個例子來解釋? –

回答

1

$.extend documents a deep flag。 scalecontext通常是對象,深標誌會告訴extend進行克隆。

另外請注意,第一個條目應該是擴展的對象,您通常不會想成爲您的默認對象。 (雖然你的情況,你每次都重新創建默認值,所以這是很好。)

所以:

var params = $.extend(
    true, // <=== The `deep` flag 
    {}, // <=== The new object that will be stored in `params` 
    {/*...your big defaults object...*/}, 
    options 
); 

簡單的例子:

(function($) { 
 
    var fooDefaults = { 
 
    text: "coolness", 
 
    style: { 
 
     color: "green", 
 
     fontWeight: "bold" 
 
    } 
 
    }; 
 
    
 
    $.fn.foo = function(options) { 
 
    var params = $.extend(true, {}, fooDefaults, options); 
 
    this.data("params", params); // Just so we can look at them 
 
    return this.each(function() { 
 
     $(this).text(params.text).css(params.style); 
 
    }); 
 
    }; 
 
    
 
})(jQuery); 
 

 
var a = $("#a"); 
 
var b = $("#b"); 
 
a.foo({text: "I'm a"}); 
 
b.foo({style: {color: "blue"}}); 
 
console.log("a's text: " + a.data("params").text); 
 
console.log("a's color: " + a.data("params").style.color); 
 
console.log("b's text: " + b.data("params").text); 
 
console.log("b's color: " + b.data("params").style.color);
<div id="a"></div> 
 
<div id="b"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>