Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
notes stimulus controller
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