Using websockets with Pusher

Hi,

Im trying to connect backend updates using websockets with pusher, here is my code:

import Pusher from 'pusher-js';

Pusher.log = (msg) => {
  console.log(msg);
};

const pusher = new Pusher('<key>', {
  cluster: '<cluster>',
});

const subscribedChannel = pusher.subscribe('test');

class TurboCableStreamSourceElement extends HTMLElement {
  async connectedCallback() {
    Turbo.connectStreamSource(this);
    subscribedChannel.bind('update', function (data) {
      this.dispatchMessageEvent(data)
    });
  }

  disconnectedCallback() {
    Turbo.disconnectStreamSource(this)
    if (this.subscription) this.subscription.unsubscribe()
  }

  dispatchMessageEvent(data) {
    const event = new MessageEvent("message", { data })
    return this.dispatchEvent(event)
  }

  get channel() {
    const channel = this.getAttribute("channel")
    const signed_stream_name = this.getAttribute("signed-stream-name")
    return { channel, signed_stream_name }
  }
}

customElements.define("turbo-cable-stream-source", TurboCableStreamSourceElement)

Pusher is receiving the event in the console but I can’t connect it with Turbo, what am I doing wrong?

Pusher console screenshot:

1 Like