1

I've run into an error in which my CoffeeScript doesn't execute an AJAX GET request when a given page initially loads; only after navigating to said page, then hitting refresh does the request go through. The script:

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("")               

jQuery ->
    new Notifications
iThompkins
  • 155
  • 1
  • 12
  • 1
    May be due to turbolinks. See: [this answer](https://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links) – Chris Kerlin Jun 19 '18 at 18:00
  • @ChrisKerlin is probably right, you probably want `$(document).on('turbolinks:load', -> new Notifications)` instead of `jQuery -> new Notifications`. Sorry, I should have noted this last time. – mu is too short Jun 19 '18 at 19:27
  • You two are correct, adding mu is too short's line makes the script send a GET request on every page load. However, not the subsequent POST request (handled by handleClick) no longer works upon clicking $("[data-behavior='notifications-link']"). Thoughts? – iThompkins Jun 20 '18 at 00:37

0 Answers0