In app notifications using stimulus and rails ujs

I am trying to implement in app notifications using stimulus and running into a problem with data-targets not being in scope in a Rails.ajax sucess action. In my controller I have:

  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

  }

this.unreadCountTarget is undefined in handleSucces(). What is the correct way to do this? How do I access the target?

1 Like

ok, i got the answer.
I need to add .bind(this)

1 Like