未捕获的引用错误,通知未定义

uncaught reference error, notification not defined

我正在尝试向我的 rails 应用添加通知。基本上我从 JSON 端点获取它们,我尝试使用一些 CoffeescriptHere's the JSON array 获取它们并将它们附加到我的 html。问题出在 handleSuccess 方法中,我收到未捕获的引用错误,通知未定义

notifications.js.coffee

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

  setup: ->
   $.ajax(
      url: "/notifications.json"
      dataType: "JSON"
      method: "GET"
      success: @handleSuccess
    )

  handleSuccess: (data) =>
   console.log(data)
   items = $.map data, (notification) ->
      "<a class='dropdown-item' href='#{notification.url}'># 
      {notification.action} #{notification.notifiable.type}</a>"

jQuery ->
 new Notifications

我从 localhost:3000/notifications.json

得到了什么

[{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"} ,"url":"/lists/10#list_10"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/10#list_10"},{"actor":"emanuelcoen" ,"action":"liked","notifiable":{"type":"your list"},"url":/lists/10#list_10"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/10#list_10"},{"actor":"emanuelcoen","action":"liked","notifiable" :{"type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17" },{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{ "type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"}, {"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url" :"/lists/17#list_17"},{"actor":"emanuelcoen","action":"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"},{"actor":"emanuelcoen","action" :"liked","notifiable":{"type":"your list"},"url":"/lists/17#list_17"}]

您传递给 $.map 的函数中存在缩进错误。它下面的字符串必须缩进,否则它会假定您正在传递一个空函数来映射,并且它后面的行会引发错误,因为 notification 未定义。

  handleSuccess: (data) =>
   console.log(data)
   items = $.map data, (notification) ->
     "<a class='dropdown-item' href=''>#{notification.actor}</a>"

更新

关于您关于通知未显示在页面上的评论 - 您没有调用任何代码来将您生成的 html 字符串添加到 DOM。您可以为此使用 $.append

  handleSuccess: (data) =>
   console.log(data)
   for notification in data
     @notifications.append(
       "<a class='dropdown-item' href=''>#{notification.actor}</a>")

不需要在通知数组上使用 $.map,因为我们只是在另一个循环中渲染它们,所以我将其替换为单个 Coffeescript 理解。