我有一个CoffeeScript,它在页面加载时GETsJSON数据,并且应该在元素带有/
data-behavior='notifications']
作为属性的单击。整个脚本:
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("")
$(document).on('turbolinks:load', -> new Notifications)
我假设你有一个NotificationsController
,因为这是你POST
去的地方。因此,请确保您的mark_as_read
方法响应 js 格式,并且您提到的脚本是与该方法关联的视图(mark_as_read.coffee.erb
(
随意在评论中提出额外的问题,除非我的建议不完全合适。