Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way of passing additional data via custom events?

I need to pass data between two autonomic user scripts - ideally without touching the unsafeWindow object - and I thought using custom events would be the way to go. I thought of something like this (let us disregard the MSIE model for the purpose of the example):

addEventListener("customEvent", function(e) {   alert(e.data); });  var custom = document.createEvent("HTMLEvents"); custom.initEvent("customEvent", true, true); custom.data = "Some data..."; dispatchEvent(custom); 

This works nicely in the standard Javascript environment and within one user script, but when the event is fired by the user script and caught outside of it or inside another user script, the data property is undefined in Chromium. I suppose I could just save the passed data in the sessionStorage, but it is far from seamless. Any other elegant solutions? Perfection need and can be achieved, I can feel it.

like image 270
Witiko Avatar asked Feb 23 '12 16:02

Witiko


People also ask

What is the purpose of custom events?

Why using custom events. The custom events allow you to decouple the code that you want to execute after another piece of code completes. For example, you can separate the event listeners in a separate script. In addition, you can have multiple event listeners to the same custom event.

What are custom events and how is it implemented?

Custom events allow us to run the function outside of the script. It is possible to attach events in other file or script and run them. It is possible to attach multiple listeners to the same event.

What are the two types of custom events?

Custom events can be created in two ways: Using the Event constructor. Using the CustomEvent constructor.


2 Answers

Yes, you can use a MessageEvent or a CustomEvent.

Example usage:

//Listen for the event window.addEventListener("MyEventType", function(evt) {     alert(evt.detail); }, false);  //Dispatch an event var evt = new CustomEvent("MyEventType", {detail: "Any Object Here"}); window.dispatchEvent(evt); 
like image 60
Digital Plane Avatar answered Sep 30 '22 17:09

Digital Plane


pass object with more details as attributes:

var event = new CustomEvent('build', { detail: { 'detail1': "something", detail2: "something else" }});  function eventHandler(e) {   log('detail1: ' + e.detail.detail1);   log('detail2: ' + e.detail.detail2); } 

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

like image 33
Amit G Avatar answered Sep 30 '22 16:09

Amit G