Rails 加载时触发 JS 委托事件?

Rails JS delegation event triggering on load?

我试图在单击时从会话中删除一些值,但它似乎在没有单击(重新加载)的情况下被触发。

这是我的代码(咖啡 + erb):

  $(document).on "click", ".top-bar[data-chatbox-id='<%=chat.id%>'] .fa-times", (e) ->
    $box_position = $("div.chat_box[data-chatbox-id='<%=chat.id%>']").position().left
    $("div.chat_box[data-chatbox-id='<%=chat.id%>']").remove()

    ## ################### LINE BELOW IS THE ONE CAUSING PROBLEMS #######
    <% session[:chatrooms].delete(chat.id) %>

    chats = $('.chat_box')
    chats.each (index, element) =>
      if $(element).position().left < $box_position
        $(element).css( 'right', '-=' + 310 + 'px' )

重新加载后会话似乎被清除了 - 它不应该只在点击时触发吗?

我唯一想到的是:"If the selector is null or omitted, the event is always triggered when it reaches the selected element.",但我之前使用以下方法创建了所选元素:

$(document.body).append("<%= j render '/chatrooms/chatroom' %>")

那是因为您正在评估运行时的会话删除,而这不是您想要的。您想在单击事件时执行删除。

为此,您可以在点击时执行 Ajax 请求,在控制器级别调用会话删除。