Creating an HTML view – stock-price.html

In the previous step, Creating a reactive controller—StockPriceEventController, we mapped a Flux stream to the "/stocks/price/{stockCode}" URL. In this step, let's create a view to show the current value of the stock on the screen.

We will create a simple static HTML page (resources/static/stock-price.html) with a button to start retrieving from the stream. The following snippet shows the HTML:

    <p>
<button id="subscribe-button">Get Latest IBM Price</button>
<ul id="display"></ul>
</p>

We want to create a JavaScript method to register with the stream and append new elements to a specific div. The following snippet shows the JavaScript method:

    function registerEventSourceAndAddResponseTo(uri, elementId) {
var stringEvents = document.getElementById(elementId);
var stringEventSource = new EventSource(uri);
stringEventSource.onmessage = function(e) {
var newElement = document.createElement("li");
newElement.innerHTML = e.data;
stringEvents.appendChild(newElement);
}
}

The EventSource interface is used to receive server-sent events. It connects to a server over HTTP and receives events in a text/event-stream format. When it receives an element, the onmessage method is called. The connection remains open until the close method is called.

The following snippet shows the code to register the onclick event for the get latest IBM price button:

    addEvent("click", document.getElementById('subscribe-button'), 
function() {
registerEventSourceAndAddResponseTo("/stocks/price/IBM",
"display");
}
);
function addEvent(evnt, elem, func) {
if (typeof(EventSource) !== "undefined") {
elem.addEventListener(evnt,func,false);
}
else { // No much to do
elem[evnt] = func;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset