Last active
June 9, 2021 17:31
-
-
Save jaredcwhite/df8092ad66a80fad53e3a81767b0a451 to your computer and use it in GitHub Desktop.
CableCar + web component
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
<cable-car href="/cc/cable_car" csrf-token="94IkWdvagUHWPGVkD+VeBFVjGoM0zXAf6tgm6BPU+kEpOj2BTtI6bXJQzEDXGAF+R6Dc1ek7oNouatTMrbUy"> | |
<button | |
onclick="this.closest('cable-car').post(this, {extra: 123})" | |
data-x="1" | |
output="#show-the-things" | |
> | |
Do a thing! | |
</button> | |
<section id="show-the-things"></section> | |
</cable-car> | |
<script type="module"> | |
import CableReady from "https://cdn.skypack.dev/cable_ready" | |
import { v4 } from "https://cdn.skypack.dev/uuid" | |
window.cableCarConfig = { | |
csrfHeader: "X-CSRF-Token" | |
} | |
class CableCar extends HTMLElement { | |
connectedCallback() { | |
this.id = `uuid-${v4()}` | |
} | |
post(fromElement, params = {}) { | |
params.cable_car_dispatcher = { | |
uuid: this.id, | |
tag: fromElement.localName, | |
attributes: Object.fromEntries(Array.from(fromElement.attributes).map(attr => [attr.name, attr.value])), | |
dataset: fromElement.dataset | |
} | |
fetch(this.getAttribute("href"), { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
[window.cableCarConfig.csrfHeader]: this.getAttribute("csrf-token") | |
}, | |
body: JSON.stringify(params) | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
if (window.cableCarConfig.debug) { | |
console.log("CableCar Response:", data) | |
} | |
CableReady.perform(data) | |
}) | |
} | |
} | |
customElements.define("cable-car", CableCar) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment