Search code examples
jquerypluginsnestedextend

jQuery plugin: Define defaults for NESTED options


I would like to define defaults for nested options like this:

$("div").filters({
          url     : 'url.example.com'
          filters : {
              'projects'    : {
                    'type'  : 'dropdown',
                    'min'   : 1,
                    'max'   : 10,
                    'htmlOptions': {
                         'name' : 'projects',
                         'class': 'filters',
                         'id'   : 'project-filter',
                     }                          
               },
               'another'    : {
                    'type'  : 'dropdown'
               }
               ...
          }
});

I use jQuery $.extend() to merge these with the defaults in my plugin code like this:

settings = $.extend(defaults,options);

My code is too big so I cannot put all of it here.

The problem I am having is that settings.url works, but I don't know how to do the same with settings.filters because I don't know how many filters the developer is going to want to put here.

Can anyone suggest a better method of dealing with this maybe?


Solution

  • Because you want to allow the developer to name the filters whatever they want, I assume you don't want to set any defaults for each specific filter (you don't know their names!).

    However, you need to set a default empty object for filters. So your defaults could be:

    var defaults = {
        url : '',
        filters: {}
    };
    

    Now, after the merge, you need to iterate over the filters object to see if there are any filters passed in.

    See this SO question: iterating-a-javascript-objects-properties-using-jquery

    So you need something like this:

    $.each(settings.filters, function(filterName, value) {
        alert(filterName + ": " + value);
    });
    

    where value will be your filter object {}

    You can use this each loop to access all properties inside a filter object.

    However, if you want the developer to be able to initialise only some properties of a filter - like in your example, where filter another has only type specified - you need to extend each filter with a set of default filter properties.