简体   繁体   中英

handle_event not working for Phoenix LiveView example

https://github.com/katpavan/liveview-testapp/blob/master/lib/liveviewapp_web/live/foo_live.ex

foo_live.ex :

defmodule LiveviewappWeb.FooLive do
  use LiveviewappWeb, :live_view
  require Logger


  @impl true
  def mount(_params, _session, socket) do
    {:ok, assign(socket, msg: "this is a message", results: %{})}
  end

  def render(assigns) do
    ~L"""
    <h1>Hello</h1>
    <div phx-keydown="keydown" phx-target="window">
    <%= @msg %>
    </div>      
    """
  end

  def handle_event("keydown", %{"key" => key}, socket) do
    Logger.debug "Var value: #{inspect(key)}"
    {:noreply, assign(socket, msg: key)}
  end
end

this is what I see when I goto the page. But when I click on the text in the div and type, the handle_event doesn't fire.

在此处输入图片说明

There are few ways to achieve this:

  1. Setting tabview=0 to div, refer to this answer for more details:

    <div id="test" phx-keydown="keydown" tabindex="0">

  2. Using phx-window-keydown , however this will make the handle global:

    <div id="test" phx-window-keydown="keydown">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM