【发布时间】:2019-02-05 18:19:29
【问题描述】:
我正在尝试在我的 rails 应用程序中包含通知,并且我正在按照本教程的信函https://gorails.com/episodes/in-app-navbar-notifications
一切顺利,直到我尝试使用 Javascript 获取通知 div,我应该在其中附加来自 JSON 端点的通知。但不知何故,我无法获取 div,因此整个以下逻辑都失败了。
如果您需要更多代码,我很乐意分享我的 github 存储库。非常感谢一些帮助:)
_navbar.html.erb
<div class="navbar-listy-right hidden-xs hidden-sm">
<% if current_user.is_a?(User) %>
<!-- Avatar with dropdown menu -->
<div class="btn-group dropleft" data-behavior="notifications">
<a class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" href="#" data-behavior="notifications-link">
<i class="far fa-bell icon-selector"></i><span data-behavior="unread-count"></span>
</a>
<div class="dropdown-menu" data-behavior="notification-items">
</div>
</div>
notifications.js.coffee
class Notifications
constructor: ->
@notifications = $("[data-behavior='notifications']")
@setup() if @notifications.length > 0
setup: ->
console.log(@notifications)
$("[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(0)
)
handleSuccess: (data) =>
if data.length > 0
items = $.map data, (notification) ->
"<a class= 'dropdown-item' href='#{notification.url}'> # .
{notification.actor} #{notification.action}
{notification.notifiable.type}</a>"
$("[data-behavior='unread-count']").text(items.length)
$("[data-behavior = 'notification-items']").html(items)
else
$("[data-behavior='unread-count']").text(items.length)
$("[data-behavior='notification-items']").html("<p>No new notifications</p>")
jQuery ->
new Notifications
编辑
我最初的问题是,即使是代码的第一步(即使用 jquery 获取 div @notifications 也会失败)。但是,我知道页面会加载,因为如果我放置一条警报消息,它会在页面加载时执行。
notifications.js.coffee
class Notifications
constructor: ->
@notifications = $("[data-behavior='notifications']")
@setup()
setup: ->
console.log(@notifications)
jQuery ->
new Notifications
【问题讨论】:
标签: ruby-on-rails json ajax coffeescript