2016-10-13 85 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>