Coffeescript 函数 运行 独立于事件

Coffeescript function running independent of event

我最近在我的 rails 应用程序中内置了一个通知功能,来自 GoRails => Here's the tut

该方法的长短在于创建一个通知模型,该模型记录涉及某些操作的用户之间的关联(即,制作 post 将创建一个通知 b/t poster 和 posted 内容的所有者)。

通知还拥有一个名为 'read' 的属性,默认情况下为 false。问题从这里开始。虽然通知已正确保存,但只要我以应该接收通知的用户身份登录,就会向我的服务器发送一个 POST 请求,将 'read' 更改为 true。下面是假定负责发出请求的脚本和视图。

class Notifications
constructor: ->
    @notifications = $("[data-behavior='notifications']")
    @setup() if @notifications.length > 0 

setup: -> 
    $("[data-behavior='notifications-link']").on "click", @handleClick ->

    $.ajax(
        url: "/notifications.json"
        dataType: "JSON"
        method: "GET"
        success: @handleSuccess
    )
handleClick: (e) =>
    $.ajax(
        url: "/notifications/mark_as_read"
        dataType: "JSON"
        method: "POST"
        success: ->
            $("[data-behavior='unread-count']").text("")                
    )
handleSuccess: (data) =>
   console.log(data) 
   items = $.map data, (notification) ->
        "<a class='dropdown-item' href='#{notification.url}'>#{notification.actor} #{notification.action} #{notification.notifiable.type}</a>"
    console.log(items)

    $("[data-behavior='notification-items']").html(items)
    $("[data-behavior='unread-count']").text(items.length)
    if items.length is 0
        $("[data-behavior='unread-count']").text("")               

jQuery ->
     new Notifications

和视图:

        <li class="nav-item dropdown" data-behavior='notifications' data-behavior="notifications-link">
      <a id="notificationsDD" href="#" class="nav-link dropdown-toggle" data-toggle="dropdown">
        <%= fa_icon("bell") %><span data-behavior='unread-count'></span>
      </a>

      <div class="dropdown-menu" data-behavior="notification-items" aria-labelledby="notificationsDD">
      <!--
      <a class='dropdown-item' href='#'>yeo</a>
       -->
      </div>
    </li>

通过修改脚本,@handleClick 函数似乎 运行 本身 w/o 发生了点击事件。

我猜你的 CoffeeScript 真的是这样的:

class Notifications
    constructor: ->
        @notifications = $("[data-behavior='notifications']")
        @setup() if @notifications.length > 0 

    setup: -> 
        $("[data-behavior='notifications-link']").on "click", @handleClick ->

    #...

因为这与您看到的行为相符。

在那种情况下,问题出在您的 setup 方法中:

$("[data-behavior='notifications-link']").on "click", @handleClick ->

添加方法调用括号向我们展示了问题所在:

$("[data-behavior='notifications-link']").on("click", @handleClick(->))

您在为 on 构建参数列表时使用(空)匿名函数作为其参数调用 @handleClick。您可能想将 handleClick 绑定到 'click' 事件,所以您想说:

$("[data-behavior='notifications-link']").on "click", @handleClick

@handleClick 函数作为参数传递而不调用它。