Event: off'ing an on event to perform only once

Hi There,

I think I might have a found a minor discrepancy in the event handling code of the client.

It happens because of the pattern I use to initialise sidebars - since RED.events.once(...) does not exist, I use:

var initialiseConfigNodeOnce = () => {
      RED.events.off('runtime-state', initialiseConfigNodeOnce);
RED.events.on('runtime-state', initialiseConfigNodeOnce);

Unfortunately what happens in the event handler is that the handler[evt] array is modified by the off call so that it shrinks by 1. This means the index in the for loop is off by one, i.e. one too large.

This is indeed the case, so I put in this fix, as follows:

let cpyHandlers = [...handlers[evt]];

for (var i=0;i<cpyHandlers.length;i++) {
    try {
        cpyHandlers[i].apply(null, args);
    } catch(err) {

i.e., make a shallow copy of the events array before iterating through it.

I don't know whether this is something that should be fixed or whether a once would be better approach or whether my initialising of sidebar nodes is off-by-one (so to speak).

If desired, I can put up a PR to apply the fix.

Hope it Helps!

A pr would be welcome

Ok, done --> Client/Editor Events: fix off-in-on pattern emulating once by gorenje · Pull Request #4484 · node-red/node-red · GitHub

I also removed a blank line...

1 Like

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.