我为我的 AJAX 通知代码开发了一个 coffeescript。代码本身没有问题。我遇到的问题是,我决定使用 setTimeout() 而不是 setInterval() 以避免耗尽线程并导致严重拥塞。我很少使用 coffeescript,我需要帮助来弄清楚如何正确地循环 setTimeout 函数。如何在 setTimeout 使用 getNewNotifications() 方法成功接收数据后调用递归方法调用?
notifications.coffee
class Notifications
constructor: ->
@notifications = $("[data-behavior='notifications']")
if @notifications.length > 0
@handleSuccess @notifications.data("notifications")
$("[data-behavior='notifications-link']").on "click", @handleClick
setTimeout (=>
@getNewNotifications()
), 5000
getNewNotifications: ->
$.ajax(
url: "/new_notification_check.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) =>
items = $.map data, (notification) ->
notification.template
unread_count = 0
$.each data, (i, notification) ->
if notification.unread
unread_count += 1
$("[data-behavior='unread-count']").text(unread_count)
$("[data-behavior='notification-items']").html(items)
jQuery ->
new Notifications
最佳答案
我相信您应该能够将 setTimeout
添加到 handleSuccess
中,这将创建您正在寻找的递归调用:
notifications.coffee
class Notifications
constructor: ->
@notifications = $("[data-behavior='notifications']")
if @notifications.length > 0
@handleSuccess @notifications.data("notifications")
$("[data-behavior='notifications-link']").on "click", @handleClick
setTimeout (=>
@getNewNotifications()
), 5000
getNewNotifications: ->
$.ajax(
url: "/new_notification_check.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) =>
items = $.map data, (notification) ->
notification.template
unread_count = 0
$.each data, (i, notification) ->
if notification.unread
unread_count += 1
$("[data-behavior='unread-count']").text(unread_count)
$("[data-behavior='notification-items']").html(items)
setTimeout (=>
@getNewNotifications()
), 5000
jQuery ->
new Notifications
关于javascript - 如何将 setTimeout() 与 CoffeeScript 重新同步? rails 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54836308/