Skip to content

Instantly share code, notes, and snippets.

@bqst
Created October 1, 2019 14:27
Show Gist options
  • Select an option

  • Save bqst/08b59afe53258c8f75014a7434de4f0e to your computer and use it in GitHub Desktop.

Select an option

Save bqst/08b59afe53258c8f75014a7434de4f0e to your computer and use it in GitHub Desktop.

Revisions

  1. bqst created this gist Oct 1, 2019.
    41 changes: 41 additions & 0 deletions notifications.js.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    # 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