Skip to content Skip to sidebar Skip to footer

Node .on Method Firing Too Many Times

I have an Electron app that presents a directory listing to the user. When the user clicks a button my interface script, interface.js, clears the container div and sends a message

Solution 1:

You are subscribing to ipcRenderer.on after every button click which is causing multiple subscriptions. Try to define the ipcRenderer.on event handler outside click event and it should work fine.

Something like this -

button.addEventListener('click', function(){ showDialogue( this ); }, false );


ipcRenderer.on( 'list-directory-reply', function( event, contents ) {
    // ipcRenderer event handler
});

showDialogue(select) {
    ipcRenderer.send( 'list-directory', './files/documents/' );
}

Solution 2:

As @planet_hunter mentioned, you are setting up a listener every time showDialogue() is called. You need to remove the listener or move the listener outside of the calling function.

However, I find a cleaner solution is to use the .once command. This behaves like .on, but instead of manually having to remove the .on listener (which you haven't done) it removes itself.

showDialogue( select ) {
    // clear the dialogue// some other stuff
    ipcRenderer.send( 'list-directory', './files/documents/' );
    ipcRenderer.once( 'list-directory-reply', function( event, contents ) {
        console.log( contents );
        if ( contents.length > 0 ) {
            // add contents to the dialogue
        }
    } );
}

Post a Comment for "Node .on Method Firing Too Many Times"