All threads / in app notifications using stimulus and ujs

Ask A Question

Notifications

You’re not receiving notifications from this thread.

in app notifications using stimulus and ujs

Joel asked in General

I am attempting in app notifications similar to how Chris did it in the tutorial but trying to update it to use Stimulus but i my data-target doesn't seem to be in scope in the ajax success callback. Here is the relevent code:

  getNewNotes() {
    Rails.ajax(
      {
        url: "/notes.json",
        type: "GET",
        success: this.handleSuccess
      }
    )
  }


  handleSuccess(data) {
    const items = $.map(data, note => { return note.template })
    console.log(items.length)
    console.log(data[0].unread)
    let unreadCount = 0
    $.each(data, (i, note) => {
      if (note.unread) {
        unreadCount += 1
      }
    });
    this.unreadCountTarget.innerHTML = unreadCount

  }

Can anyone point me in the right direction to get this working using stimulus?

You have to .bind(this) if you want to retain the context/scope when passing in a function for a callback, otherwise it will use the callback's scope for this.

        success: this.handleSuccess.bind(this)

Javascript is real weird.

Thanks! Makes me love Ruby more every time I have to jump into Javascript.

Did you ever finish this? I am looking to do the exact same thing.

yes , I did. Did you have any specific questions about it?

Thanks for the reply Joel. I managed to get the Notifications displaying, and extended the Dropdown Controller from Chris' tailwindcss/stimulus repo - https://github.com/excid3/tailwindcss-stimulus-components

Now I'm in the process of converting the jQuery that you posted to ES6, I was just curious if you had a complete gist/repo of the implementation to compare to!

I am still using some jQuery, but here is the stimulus controller I am using...

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 33,665+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.