2013-07-28 31 views
6

我使用jQuery extend在一個插件來覆蓋默認參數。但是,我有一個問題。jQuery的擴展覆蓋錯誤的價值觀

這裏是我的默認設置陣列:

slider.settings = { 
      background: { 
       animation : { 
        direction : 'horizontal', 
        increment : 15 //can be any number 
       } 
      } 
     } 

現在,我要覆蓋direction參數。這裏,我將使用extend合併數組:

settingsToOverwrite = { 
     background:{ 
      animation:{ 
       direction:'vertical' 
      } 
     } 
    } 

現在,我合併兩個:

slider.settings = $.extend(slider.settings, options) 

我可以看到方向值已經更新。但是,增量不再存在。我知道爲了避免這個問題,我只能在第一級設置參數,但是我按照自己的方式看到了更多的代碼清晰度。有沒有辦法做到這一點?如果沒有,我會改變一切只有一個深度。

回答

11

默認情況下,jQuery.extend()只比較直接的性質,執行「淺合併「。由於兩個對象background,它只是需要從第二個對象的整個background

但是,pass a true作爲第一個參數,而jQuery.extend()將執行「深度合併」。

slider.settings = $.extend(true, slider.settings, options); 

而且,由於第1 Objecttarget,將改性和return倒是,你可以只用更新slider.settings

$.extend(true, slider.settings, options); 

而且,如果你寧願有合併的new Object,您必須自己創建:

slider.settings = $.extend(true, {}, slider.settings, options); 
+0

你學習新的東西每天:)很好 –

2

你是對的,這顯然發生,因爲jQuery的延長是「淺延伸」的對象。因此更換整個「動畫」屬性。

要解決這個問題,用你的白蘭地花花公子deepExtend:

Object.deepExtend = function(destination, source) { 
    for (var property in source) { // loop through the objects properties 
    if (typeof source[property] === "object") { // if this is an object 
     destination[property] = destination[property] || {}; 
     Object.deepExtend(destination[property], source[property]); // recursively deep extend 
    } else { 
     destination[property] = source[property]; // otherwise just copy 
    } 
    } 
    return destination; 
}; 

可以按如下方式使用它:

slider.settings = Object.deepExtend(slider.settings, options); 
+0

你有沒有我會用slider.settings做什麼的例子?我的意思是我不知道如何使用這個功能。謝謝。 – CoachNono

+0

剛剛添加回答:) –

+0

令人驚歎的謝謝! – CoachNono