Last active
August 11, 2019 11:26
-
-
Save tlcheah2/92f1f89c4d04342c992a22c35e6c9ec4 to your computer and use it in GitHub Desktop.
This pug file show how to write script within pug template and how to connect event stream connection with backend
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
h1 Quote of The Day | |
h3 List of Quotes that we crawled | |
p Refresh every minute and you will saw a new quote | |
ul#quoteList | |
script. | |
let quotes = []; | |
var eventSource = new EventSource('quoteEvent'); | |
// Listen to New Quote Event | |
eventSource.addEventListener('newQuote', function (e) { | |
const data = JSON.parse(e.data); | |
console.log('data', data); | |
// Create a <li> node | |
var node = document.createElement("LI"); | |
// Create a text node | |
var textnode = document.createTextNode(data.quote); | |
// Append the text to <li> | |
node.appendChild(textnode); | |
// Apeend <li> to <ul> | |
document.getElementById("quoteList").appendChild(node); | |
}); | |
// When connection is closed, we have to stop subscribing to the event to avoid memory leak | |
eventSource.addEventListener("closedConnection", function (ev) { | |
eventSource.close(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment