I’m building my first jQuery plugin. It takes JSON data and loads it into table. I’ve got most of the logic done, I’m just having trouble building the default options array.
What I would like to do is pass in an options array like this:
/* Column array format:
cols:
[colname:
{
title: 'Column Title', // Column title for display (if not specified, will
// use 'colname' value instead.
sorttype: 'text', // 'text', 'dropdown' or 'none'
},
nextcolname:
{
...
},
...
]
*/
What I’m having problems with is packing the default array if no options are passed in. Here’s what I have:
var settings = $.extend ({
'cols' : 'auto',
'sortable' : 'true' //turn off sorting altogether with this option.
}, options);
var index = '';
var element = '';
var colname = '';
// No columns specified. That's OK, grab keys from first JSON element.
if (settings.cols == 'auto')
{
settings.cols = Object.keys(data[0]);
$.each(settings.cols, function(index, colname){
settings.cols[colname].title = colname;
settings.cols[colname].sorttype = 'text';
})
}
First of all, style-wise, does it look like I’m going about this the right way? Do both the format of the options array and the way I’m parsing it make sense? Second of all, the settings.cols[colname].title returns a type error because it doesn’t exist (of course). How do I populate this object so I can use it effectively so that I can iterate through it?
The line where you assign settings.cols isn’t going to work … it assigns an array rather than a property map. Try this instead:
Here’s a complete test that shows the difference. settings1 comes out valid using the above, but trying to access settings2 throws an error: