Skip to content

Instantly share code, notes, and snippets.

@joelcahalan
Created November 6, 2019 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelcahalan/204fe65800112f6a1f401a2064c887bd to your computer and use it in GitHub Desktop.
Save joelcahalan/204fe65800112f6a1f401a2064c887bd to your computer and use it in GitHub Desktop.
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