luthien
luthien

Reputation: 1305

Event listener and local data storage

Can I store the data received by an event through a listener function into a variable in my HTML file (I mean out of the scope of the listener function)?

<div id="id1"></div>
<script>
    var a = document.querySelector('#id1');
    a.addEventListener('fooEvent', function(e){
        console.log(e.detail);
    });
    var event = document.createEvent("CustomEvent");
    var data = "[1,2,3]";
    event.initCustomEvent("fooEvent", true, true, data);
    a.dispatchEvent(event);
</script>

JSFIDDLE: https://jsfiddle.net/dtxwr6h9/

In this example, I want to have access to the e.detail data outside of the listener function. Is this possible somehow?

Thanks in advance!

Upvotes: 1

Views: 1416

Answers (1)

ManoDestra
ManoDestra

Reputation: 6503

Sure. Just store it in a variable or in localStorage using JSON.stringify after you've captured the event. Then unbind the event handler, if necessary.

E.g.

<script>
    // variable here for storage
    var storedObj;
    var a = document.querySelector('#id1');
    a.addEventListener('fooEvent', function(e){
        console.log(e.detail);
        // store it in your outer scoped variable, or localStorage, if you prefer.
        storedObj = e.detail;
    });
    var event = document.createEvent("CustomEvent");
    var data = "[1,2,3]";
    event.initCustomEvent("fooEvent", true, true, data);
    a.dispatchEvent(event);
</script>

Upvotes: 1

Related Questions