Skip to content

Commit

Permalink
Extract ajax and events into own utils modules
Browse files Browse the repository at this point in the history
  • Loading branch information
tvdeyen committed Apr 7, 2020
1 parent d72e641 commit 3ed77ae
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 48 deletions.
3 changes: 2 additions & 1 deletion app/javascript/alchemy/admin/node_tree.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Sortable from "sortablejs"
import { on, ajax } from "./utils"
import ajax from "./utils/ajax"
import { on } from "./utils/events"

function displayNodeFolders() {
document.querySelectorAll("li.menu-item").forEach((el) => {
Expand Down
47 changes: 0 additions & 47 deletions app/javascript/alchemy/admin/utils.js

This file was deleted.

40 changes: 40 additions & 0 deletions app/javascript/alchemy/admin/utils/ajax.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
function buildPromise(xhr) {
return new Promise((resolve, reject) => {
xhr.onload = () => {
try {
resolve({
data: JSON.parse(xhr.responseText),
status: xhr.status
})
} catch (error) {
reject(new Error(JSON.parse(xhr.responseText).error))
}
}
xhr.onerror = () => {
reject(new Error(xhr.statusText))
}
})
}

function getToken() {
const metaTag = document.querySelector('meta[name="csrf-token"]')
return metaTag.attributes.content.textContent
}

export default function ajax(method, url, data) {
const xhr = new XMLHttpRequest()
const promise = buildPromise(xhr)

xhr.open(method, url)
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8")
xhr.setRequestHeader("Accept", "application/json")
xhr.setRequestHeader("X-CSRF-Token", getToken())

if (data) {
xhr.send(JSON.stringify(data))
} else {
xhr.send()
}

return promise
}
16 changes: 16 additions & 0 deletions app/javascript/alchemy/admin/utils/events.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export function on(eventName, baseSelector, targetSelector, callback) {
document.querySelectorAll(baseSelector).forEach((baseNode) => {
baseNode.addEventListener(eventName, (evt) => {
const targets = Array.from(baseNode.querySelectorAll(targetSelector))
let currentNode = evt.target

while (currentNode !== baseNode) {
if (targets.includes(currentNode)) {
callback.call(currentNode, evt)
return
}
currentNode = currentNode.parentElement
}
})
})
}

0 comments on commit 3ed77ae

Please sign in to comment.