Skip to content

Instantly share code, notes, and snippets.

@bqst
Created October 1, 2019 14:27
Show Gist options
  • Save bqst/08b59afe53258c8f75014a7434de4f0e to your computer and use it in GitHub Desktop.
Save bqst/08b59afe53258c8f75014a7434de4f0e to your computer and use it in GitHub Desktop.
notifications.js.coffee
# app/assets/javascripts/notifications.coffee
class Notifications
constructor: ->
@getNewNotifications()
@notifications = $("[data-behavior='notifications']")
if @notifications.length > 0
@handleSuccess @notifications.data('notifications')
$("[data-behavior='notifications-link']").on "click", @handleClick
# setInterval (=>
# @getNewNotifications()
# ), 5000
getNewNotifications: ->
$.ajax(
url: Routes.notifications_path({format: 'json'})
dataType: 'JSON'
method: 'GET'
success: @handleSuccess
)
notificationClick: (e) =>
$.ajax(
url: Routes.mark_as_read_notification_path(e.currentTarget.id, {format: 'json'})
dataType: 'JSON'
method: 'POST'
)
handleSuccess: (data) =>
if data?
items = $.map data.notifications, (notification) ->
notification.template
$("[data-behavior='unread-count']").text(data.unread_count)
$("[data-behavior='notification-items']").html(items) if items.length > 0
$("[data-behavior='notification-link']").on 'click', @notificationClick
jQuery ->
# new Notifications
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment