LiveView learning application

HI there.

I recently added “beep” to a live view page and I also used the mounted callback.
However, I did not do it by calling beep() directly in the mounted callback. Instead, I used handleEvent like this:

In app.js:

Hooks.MyElement = {
  mounted() {
    this.handleEvent("play_beep", (payload) => {
      beep();
    });
  },
};

Then whenever my LiveView component handles an event with this kind of return:

In my_live.index.ex:

  def handle_info({SomeModule, [:something | [:happened]], _}, socket) do
    {:noreply, push_event(fetch(socket), "play_beep", %{})}
  end

So you could have the interval done in elixir instead. There are probably other ways to approach this, and my use case is not the same as yours (I don’t need an interval). Still, hopefully it helps.

Docs here: JavaScript interoperability — Phoenix LiveView v1.2.5

P.S. the client can push events too. Look at pushEvent in the docs.

P.P.S. You might have to upgrade your phoenix_live_view version.

1 Like