Home > Software engineering >  Extend a socket.onmessage = (e) => {} without overwriting its parent
Extend a socket.onmessage = (e) => {} without overwriting its parent

Time:10-06

How can you extend the following code

// socket.js
window['socket'] = new WebSocket('wss://wss.somedomain.com:1000');
socket.onmessage = (e) => {
    let payload = JSON.parse(e.data);
    if (payload.event === 'event1') {
        // do stuff here which works
    }
}

// otherFile.js
// extend the socket JS socket.onmessage = (e) => {}
socket.onmessage = (e) => {
    let payload = JSON.parse(e.data);
    if (payload.event === 'event1') {
        // do more stuff on event1
    }
}

How do I extend this socket.onmessage = (e) => {} without overwriting the one in socket.js

CodePudding user response:

You probably want addEventListener instead. addEventListener lets you attach multiple callbacks such that they don't cancel each other out:

// socket.js
window['socket'] = new WebSocket('wss://wss.somedomain.com:1000');
socket.addEventListener('message', (e) => {
    let payload = JSON.parse(e.data);
    if (payload.event === 'event1') {
        // do stuff here which works
    }
});

// otherFile.js
// extend the socket JS socket.onmessage = (e) => {}
socket.addEventListener('message', (e) => {
    let payload = JSON.parse(e.data);
    if (payload.event === 'event1') {
        // do more stuff on event1
    }
});

CodePudding user response:

You could store the original socket.onmessage in a variable then call that variable in your new socket.onmessage function:

// socket.js
window['socket'] = new WebSocket('wss://wss.somedomain.com:1000');
socket.onmessage = (e) => {
    let payload = JSON.parse(e.data);
    if (payload.event === 'event1') {
        // do stuff here which works
    }
}

// otherFile.js
// extend the socket JS socket.onmessage = (e) => {}
let oldSocketOnMessage = socket.onmessage;
socket.onmessage = (e) => {
    let payload = JSON.parse(e.data);
    if (payload.event === 'event1') {
        // do more stuff on event1
    }
    oldSocketOnMessage(e);  // call the original
}
  • Related