-
-
Notifications
You must be signed in to change notification settings - Fork 315
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extract ajax and events into own utils modules
- Loading branch information
Showing
4 changed files
with
58 additions
and
48 deletions.
There are no files selected for viewing
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
This file was deleted.
Oops, something went wrong.
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
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 | ||
} |
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
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 | ||
} | ||
}) | ||
}) | ||
} |