in app notifications using stimulus and ujs
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 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!