Search code examples
polymerweb-componentcustom-element

Polymer Custom elements dataset is empty in Firefox


I have the impression that Firefox is "clearing" the data-* attributes on custom elements.

See the script below works in Chrome with native Web Components support, but in Firefox, it seems that once my click event handler is run, the dataset is empty.

document.addEventListener('DOMContentLoaded', function() {
    var popups = document.querySelectorAll('iron-image[data-popup]');
    for (var i=0; i < popups.length; i++) {
        var img = popups[i];
        console.log(img.dataset.popup);   // <--- this works

        img.addEventListener('click', function(ev) {
            var app = document.querySelector('sh-app');
            app.showPopup(ev.target.dataset.popup);  // <-- This fails, dataset is empty
        });
    }
});

Side Note: I have also tried the WebComponentsReady event, but it doesn't get fired at all for some reason.

Has anyone run into this issue before and understand the cause? Is this a bug in Polymer (<iron-image> in this case), the Web Components polyfills, or Firefox's implementation thereof?


Solution

  • Event retargeting

    Basically, you have to wrap the event using Polymer.dom to normalize it.

    document.addEventListener('DOMContentLoaded', function() {
        var popups = document.querySelectorAll('iron-image[data-popup]');
        for (var i=0; i < popups.length; i++) {
            var img = popups[i];
            console.log(img.dataset.popup);   // <--- this works
    
            img.addEventListener('click', function(ev) {
                var app = document.querySelector('sh-app');
                var event = Polymer.dom(ev); // you wrap the event using Polymer.dom
                app.showPopup(event.localTarget.dataset.popup);  // instead of target you should use localTarget
           });
       }
    });