Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

#addEventListener and customEvent

8 views
Skip to first unread message

Une Bévue

unread,
Jul 24, 2017, 1:13:07 AM7/24/17
to
This is a simple test in order to veify a feasability.

I have a simple page with :
<p id="tic">tic</p>
<p id="dif"></p>
<pre id="log"></pre>

the former <pre /> is used to logout the internal state of the script.

in the JavaScript side i generate a customEvent every second :

setInterval( function () {
let event = new CustomEvent(
"cronMessage",
{
detail: {
message: "tick",
time_in_s: Math.floor((new Date()).getTime() / 1000),
},
bubbles: true,
cancelable: true
}
);
dif.dispatchEvent(event);
}, 1 * 1000);

(dif is a global variable = to document.getElementById('dif');

here is the problem encountered :

if I listen to this event on the body, ie.:
body = document.getElementsByTagName('body')[0];
body.addEventListener('cronMessage', tictac, false);

it works well as expected.

the function "tictac" being :
function tictac (event) {
let truc = tic.innerHTML;
tic.innerHTML = (tic.innerHTML === 'tic')? 'tac' : 'tic';
let diff = event.detail.time_in_s % HOUR_IN_S;
if (diff === 0) {
dif.innerHTML = 'diff === 0';
}
console.log(`tictac (event) -> diff = ${diff}`)
}

(tic is a global variable = to document.getElementById('tic');

then in the "paragraph" <p id="dif"></p> I got 'diff === 0' (instead of
'') when the time cross an hour ( HOUR_IN_S is also a global variable =
to 60 * 60).


however when I listent to this cusstomEvent from a DOM node other tha
the body in my example, nothing is received.

for example with :
tic.addEventListener('cronMessage', tictac, false);

i think/suspect it is a question of event bubbling versus the node being
the source of the event (in my case the "paragraph" named 'tic').

what is the best way to be able to listen to a customEvent from any node
of a page ? dispatch it from the window ? the body ?

Une Bévue

unread,
Jul 24, 2017, 1:55:34 AM7/24/17
to
I found it :

the CustomEvent bubbles to ancestors of the element which fired the event.

<https://www.sitepoint.com/javascript-custom-events/>

then, better to dispatch from the deeper node and listen from the upper
in dom (body or document ans even window?)

0 new messages