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?

Reply

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.

Reply

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

Reply

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

Reply

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

Reply

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!

Reply

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

Reply
Join the discussion
Create an account Log in

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

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

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