Search code examples
javascripteventsdombrowsermozilla

browser javascript creating custom events


I don't unterstand this:

I try to create a custom event which should be fired when a list is fully loaded in a table body. Like this (executes after list is loaded):

  var event = new Event('mklistloaded', {
        name: 'listname'
  });

  document.dispatchEvent(event);

And this is the "receiving" end:

document.addEventListener('mklistloaded', function(e) {

    console.log('mklistloaded event: ' + JSON.stringify(e));

});

But console log prints out:

mklistloaded event: {"isTrusted":false}

That's quite the same as described in the mozilla example:

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

What am I doing wrong here?


Solution

  • You missed the section in the docs "Adding custom data – CustomEvent()"

    document.addEventListener('mklistloaded', function(e) {
      console.log('mklistloaded detail: ', e.detail);
    });
    // use CustomEvent() instead of Event()
    var event = new CustomEvent('mklistloaded', {
      'detail': 'listname'
    });
    
    document.dispatchEvent(event);

    Note that it seems to require using the property name detail