JSFiddle - React, Tailwind, and code Playground
by ajai jothi
HTML
returnId: <input type=""><button id="listen">Listen</button>
<div id="triggers">
</div>
<hr>
<div>
Output:
<pre></pre>
</div>
JavaScript
function fireChange(uuid) {
const url = `http://localhost:8080/events/${uuid}`;
return async () => await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
}
function onMessage(uuid, e) {
document.querySelector('pre').innerHTML += `${uuid}: ${JSON.stringify(e.data)}<br>`;
}
function createListener(uuid) {
const url = `http://localhost:8080/events/${uuid}`;
const source = new EventSource(url);
source.onmessage = onMessage.bind(this, uuid);
}
function createTrigger(uuid) {
const button = document.createElement('button');
button.innerHTML = `trigger change for ${uuid}`;
document.querySelector('#triggers').appendChild(button);
button.addEventListener('click', fireChange(uuid));
}
document.querySelector('#listen').addEventListener('click', function() {
const returnId = document.querySelector('input').value;
if (!returnId) {
return;
}
createListener(returnId);
createTrigger(returnId);
});