[英]How to merge user options with default options using jQuery's extend() when options have a property array of objects
當options對象的屬性值是對象數組時,如何使用jQUery的extend()
方法將用戶選項與默認選項合並
例:
var settings4 = $.extend({
type: 'one-panel', // 'one-panel' | 'two-panel'
sidebarTargets: [
{
targetKey: 'sidebar-one',
initialLoadPanelKey: 'panel1',
emptyPanelMessage: '',
sidebarWrapSelectorId: 'sidebar-container',
sidebarPanelWrapTemplate: '<div class="sidebar-panel {panelInitialSlideCss}" id="{panelSelectorId}" data-panel-key="{panelKey}"></div>',
showHeader: true,
headerTemplate: '<div class="sidebar-header" id="sidebar-header">Header text</div>',
},
// if sidebarSettings.type == one-panel, this is not required
{
targetKey: 'sidebar-two',
initialLoadPanelKey: 'none',
emptyPanelMessage: '<span>No Notebooks Notes Found',
sidebarWrapSelectorId: 'sidebar-container',
sidebarPanelWrapTemplate: '<div class="sidebar-panel" id="{panelSelectorId}" data-panel-key="{panelKey}"></div>',
showHeader: true,
headerTemplate: '<div class="sidebar-header" id="sidebar-header">Header text</div>',
},
{
targetKey: 'right-content-panel',
selectorId: 'sidebar-container',
cssClassLIst: 'content-panel content',
showLoader: true, // when AJAX content is loaded, show a loader spinner
loaderTemplate: '',
initialInnerContent: '',
},
{
targetKey: 'right-content-iframe-panel',
selectorId: 'sidebar-container',
cssClassLIst: 'content-panel content',
iframeNameAttribute: 'content',
template: '<iframe id="content-frame" src="default.html" name="content" width="100%" height="100%" frameborder="0"></iframe>',
}
],
}, sidebarOptions);
sidebarTargets
上方的object屬性是有問題的。 它可以在數組中包含任意數量的對象。 如何使用jQuery的擴展來合並選項並處理這樣的屬性?
恐怕您無法使用jQuery's extend
函數真正做到這一點。
如果在第一個參數中發送true
,則extend
將能夠擴展您擁有的對象 。 問題是您的對象中有Array
,並且extend
將不知道如何處理這些Array
。
如果您能夠將代碼更改為對象,則將非常有用:
var a = { a: ['a'], b: { 'c': 1 } } var b = { a: ['b'], b: { 'd': 2 } } $.extend(a, b) console.log('regular extend:') console.log(a); console.log('') var a = { a: ['a'], b: { 'c': 1 } } var b = { a: ['b'], b: { 'd': 2 } } $.extend(true, a, b) console.log('deep copy extend:') console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.