0

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sthe
  • 2,575
  • 2
  • 31
  • 48
  • Is there a set number of filters a user can initialise? Do you know all the filter names or are they created by the user and can be named whatever? – jfrej May 16 '12 at 17:42
  • I wanted to allow the developer to name them whatever they want. However, if that doesn't work. I can just hardcode all of them, because I know them. They are about 8 in total, but only two are used in some instances. So it would be better for me allow that type of flexibility if you know what I mean? – Sthe May 16 '12 at 17:57

1 Answers1

1

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.

Community
  • 1
  • 1
jfrej
  • 4,548
  • 29
  • 36