Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

160
Visualizações
Copy EventListener

I have an object literal to create a websocket connection

let websocket;

const websocketConnect = {
    conn: null,
    start: function () {
        this.conn = new WebSocket('wss://.....');
        websocket = this.conn;

        this.conn.onopen = (e) => {};
        this.conn.onmessage = (e) => {};
        this.conn.onclose = (e) => {
            this.reconnect();
        };
    },

    reconnect: function () {
        this.start();
    },
};

websocketConnect.start();

websocket.addEventListener('message', function (e) {
    /***/
});

the websocket variable is global and is assigned the websocket connection, so that I can attach an eventListener outside of websocketConnect. if the connection is lost, i try to establish a new connection via reconnect().

the problem now is that websocket is reassigned in start() and the eventListener hangs on the old websocket and not on the new one. can I copy the eventListener and assign it to the new websocket-variable?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You could create an array of functions that you wish to use for processing incoming messages:

let websocket


const websocketConnect = {
    conn: null,
    messageFunctions: [],
    start: function () {
        this.conn = new WebSocket('wss://.....')
        this.conn.onmessage = (e) => {
            for (const func of messageFunctions) func(e)
        }
        websocket = this.conn
    },
    reconnect: function () {
        websocket = null
        this.start()
    }
}
websocketConnect.messageFunctions.push((event) => {
    console.log('handler1', event)
})

websocketConnect.messageFunctions.push((event) => {
    console.log('handler2', event)
})

websocketConnect.start()

This way, your functions are not attached directly to the WebSocket, and can be called for any new WebSocket connections without duplicating the anonymous functions.

about 4 years ago · Juan Pablo Isaza Relatório

0

You could define your own addEventListener method and forward calls to the actual method, but also keep track of them. That way you can apply them again when a new connection is made.

const websocket = {
    conn: null,
    listeners: [],
    start() {
        this.conn = new WebSocket('wss://.....');
        // Restore event listeners
        for (let {event, callback} of this.listeners) {
            this.conn.addEventListener(event, callback);
        }
        this.conn.onclose = (e) => {
            this.reconnect();
        };  
    },
    reconnect() {
        this.start();
    },
    addEventListener(event, callback) {
        // Save event listener
        this.listeners.push({event, callback});
        if (this.conn) this.conn.addEventListener(event, callback);
    }
}

websocket.start();
websocket.addEventListener('message', function (e) {
    /***/
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda