jqueryjquery-data

jQuery Data Attribute with Prefix Override Object


I have built my own custom jQuery plugin and I'm trying to override the default options using HTML data attributes. I have added a prefix (pager) to each one so my final mark-up is:

<div class="pager" data-pager-page="1"></div>

Now say I have an object:

var options = { page: 0 };

I'd like to override the options by saying something like:

var o = $.extend({}, options, $('.pager').data('pager'));

However this doesn't work. After doing abit of debugging I discovered $('.pager').data('pager') was returning undefined. If I say:

$('.pager').data();

This returns the following object:

{ pagerPage: 1 }

I guess I would need some way to convert this object to the one I need. Please note that I would like to add many options and code should handle this without me having to handle each individual option.

I'm sure others have run into this problem and I'd appreciate any help. Thanks


Solution

  • Incase anyone is interested the following code did the trick:

    var data = $('.pager').data();
    
    for (var p in data) {
        if (data.hasOwnProperty(p) && /^pager[A-Z]+/.test(p)) {
            var shortName = p[5].toLowerCase() + p.substr(6);
            data[shortName] = data[p];
        }
    }
    
    var o = $.extend({}, options, data);
    

    Note: Replace 5 with the length of the prefix and 6 with the length + 1. Hope this helps.

    Thanks Kevin for pointing me in the right direction.