简体   繁体   中英

Coffee script conditional rails

I have a website with a little bell, and when a new notification comes, the @notifications.lenght is passed via javascript for showing the number of notifications. What i just want is to show the number of notification if there is one or more notifications and if there is no notification showing just the bell like this :

钟

Actually if the user has no notification the page displays this :

钟0

If i click the bell :

钟

Witch is good, but when i refresh the page :

铃3

Here is my coffee :

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) =>

    items = $.map data, (notification) ->
      "<a class='dropdown-item' href='#{notification.url}'>#{notification.actor} #{notification.action} </a>"

    $("[data-behavior='unread-count']").text(items.length) 
    $("[data-behavior='notification-items']").html(items)





jQuery ->
  new Notifications

How could i pass an empty string if the @notifications.lenght == 0 ?

In your handle success method, replace the code that set the total items to:

$("[data-behavior='unread-count']").text(parseInt(items.length) || "");

If items.length is 0 , it will set an empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM