JavaScript custom Event Listener
var evt = document.createEvent("Event");
evt.initEvent("myEvent",true,true);
// custom param
evt.foo = "bar";
//register
document.addEventListener("myEvent",myEventHandler,false);
//invoke
document.dispatchEvent(evt);
Here is the way to do it more locally, pinpointing listeners and publishers:
http://www.kaizou.org/2010/03/generating-custom-javascript-events/
How to capture custom events?
As Moritz stated, you will need to fire the event on the child, as it is the most-inner element. That way the event bubbles up to each parent. The target
of the event will always be the child, but currentTarget
of the event will be the current element as it goes up the chain.
You must make sure that useCapture
is true
, for the ancestor elements you want the event to be picked-up for. See: EventTarget.addEventListener
.
useCapture
A
Boolean
indicating that events of this type will be dispatched to the registeredlistener
before being dispatched to anyEventTarget
beneath it in the DOM tree.
Events that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. See DOM Level 3 Events and JavaScript Event order for a detailed explanation. If not specified,
useCapture
defaults tofalse
.
If you remove the useCapture
param (the second param) from parent.addEventListener
, only the grand-parent will get picked-up, following the child. It will not break the chain, unless you cancel the event in the child.
Note: If you are triggering a non-native event, it is preferred to use the CustomEvent
constructor. Again, you could just call the constructor directly if you wanted. This is just a browser-safe wrapper.
let grandParent = document.getElementById('x-grand-parent');let parent = document.getElementById('x-parent');let child = document.getElementById('x-child');
grandParent.addEventListener('custom-event', (e) => console.log(e.currentTarget.id), true);parent.addEventListener('custom-event', (e) => console.log(e.currentTarget.id), true);child.addEventListener('custom-event', (e) => console.log(e.currentTarget.id));
triggerCustomEvent(child, 'custom-event');
function triggerCustomEvent(el, eventName, options) { let opts = Object.assign({ canBubble: true, cancelable: true, detail: {} }, options); let event = null; if (window.CustomEvent && typeof window.CustomEvent === 'function') { event = new CustomEvent(eventName, { detail: opts.detail }); } else { event = document.createEvent('CustomEvent'); event.initCustomEvent(eventName, opts.canBubble, opts.cancelable, opts.detail); } el.dispatchEvent(event);}
<div id="x-grand-parent"> <div id="x-parent"> <p id="x-child"> Hello World </p> </div></div>
custom event listener on a dom node
You could register custom events handler using addEventListener
method. BTW this approach is recommended for native events as well. Inline handlers are bad because they are mixing view (HTML) with logic (js).
var elem = document.getElementById("bar");
elem.addEventListener('foo', function() { console.log('foo event on bar')})
document.getElementById('foo').addEventListener('click', function() { var event = new CustomEvent('foo'); elem.dispatchEvent(event);})
<button id="bar">Bar</button><button id="foo">Trigger Foo</button>
When I trigger custom event with parameters, parameters from event handler is undefined
When you create object new DataLoader()
and declaring let el
, the el
is always undefined.
So you must assign some value to that.
You must do something like this
function DataLoader(elem) {
let el = elem;
//When data is loaded {
el.dispatchEvent(new CustomEvent('myevent', { number: 123 }));
//}
return el;
}
and then create object like
loader = new DataLoader(document.body);
For more info CustomEvent MDN
Your code is unclear. Do like this based on your requirement.
var obj = document.createElement('section')
obj.addEventListener("cat", function(e) { console.log(e.detail)});
// create and dispatch the event
var event = new CustomEvent("cat", {
detail: {
hazcheeseburger: true
}
});
obj.dispatchEvent(event);
Related Topics
Understanding JavaScript Scope with "Var That = This"
Map Isn't Showing on Google Maps JavaScript API V3 When Nested in a Div Tag
Array Like Objects in JavaScript
Refused to Execute a JavaScript Script. Source Code of Script Found Within Request
When to Use the Double Not (!!) Operator in JavaScript
Clearing Localstorage in JavaScript
JavaScript Pass Object as Reference
Setting Div Width and Height in JavaScript
Convert an Image into Binary Data in JavaScript
JavaScript Triple Greater Than
Chrome Extension: Make It Run Every Page Load
Angular2 Component's "This" Is Undefined When Executing Callback Function
How Dangerous Is It in JavaScript, Really, to Assume Undefined Is Not Overwritten
How to Use Optional Chaining in Node.Js 12
Is There a Downside to Using Es6 Template Literals Syntax Without a Templated Expression
ASP.NET MVC 3 Razor: Include JavaScript File in the Head Tag
How to Scroll the Window Using Jquery $.Scrollto() Function
Browserify, Babel 6, Gulp - Unexpected Token on Spread Operator