2016-10-13 12 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文書a deepフラグ。 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>