Created
November 6, 2019 16:18
-
-
Save joelcahalan/204fe65800112f6a1f401a2064c887bd to your computer and use it in GitHub Desktop.
notes stimulus controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "stimulus"; | |
export default class extends Controller { | |
static targets = ["notes", "unreadCount"]; | |
connect() { | |
this.getNewNotes(); | |
if (this.data.has("refreshInterval")) { | |
this.startRefreshing(); | |
} | |
} | |
disconnect() { | |
this.stopRefreshing(); | |
} | |
stopRefreshing() { | |
if (this.refreshTimer) { | |
clearInterval(this.refreshTimer); | |
} | |
} | |
startRefreshing() { | |
setInterval(() => { | |
this.getNewNotes(); | |
}, this.data.get("refreshInterval")); | |
} | |
getNewNotes() { | |
Rails.ajax({ | |
url: "/notes.json", | |
type: "GET", | |
success: this.handleSuccess.bind(this) | |
}); | |
} | |
handleSuccess(data) { | |
const items = $.map(data, note => { | |
return note.template; | |
}); | |
let unreadCount = 0; | |
$.each(data, (i, note) => { | |
if (note.unread) { | |
unreadCount += 1; | |
} | |
}); | |
this.unreadCountTarget.innerHTML = "" | |
if (unreadCount > 0) { | |
this.unreadCountTarget.innerHTML = unreadCount; | |
} | |
this.notesTarget.innerHTML = ""; | |
for (const item of items) { | |
this.notesTarget.insertAdjacentHTML("beforeend", item); | |
} | |
} | |
handleMouseOver(event) { | |
$.ajax({ | |
url: "/notes/mark_as_read", | |
dataType: "JSON", | |
method: "POST", | |
success: this.handleSuccess.bind(this) | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment