Reputation: 8312
I am writing a plugin for jquery, and I have used a code like this to allow users to specify options for the plugin:
var settings = $.extend({
url : 'error.json',
slotWidth : 100,
slotHeight : 100,
gridWidth : 6,
gridHeight : 3,
basketLayers : 1,
layerDirection : "vertical",
classNames : {
productPanelParent : '.products-panel-parent',
productPanelTabs : '.products-panel-tabs',
productPanelGroup : '.products-panel-container',
productPanel : '.products-panel',
productBasketParent : '.products-basket-parent',
productBasketGroup : '.products-basket-container',
productBasket : '.products-basket',
productBasketMenu : '.products-basket-menu',
basketSlot : '.basket-slot',
basketSlotFull : '.basket-slot-full',
basketSlotHelper : '.basket-slot-highlight',
product : '.product',
resetBasket : '.clearBasket',
resetLayer : '.clearLayer',
viewLayer : '.viewLayer'
}
}, options);
The problem is that when I try to override one of the classNames, the whole array is written over with null
values wherever a property wasn't specificed.
So for example, I'll do something like this:
$('#somediv').myPlugin({
gridWidth : 4,
gridHeight : 2,
classNames : {
productBasket : '.small_basket'
}
});
And the settings.classNames.productBasket
property will be the correct value, but everything is in settings.classNames will be null.
How do I get around this?
(without writing a custom function to handle default values in the array?)
Upvotes: 0
Views: 1057
Reputation: 165971
The first argument to jQuery.extend()
can be a boolean. If it's true
, then the extension is "deep" (the merge is made recursively):
var settings = $.extend(true, defaults, options);
From the docs:
The merge performed by
$.extend()
is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second object. The values are not merged... However, by passing true for the first function argument, objects will be recursively merged.
Upvotes: 1