Wednesday, January 28, 2015

A Simple Ember.js Demo for Lightstreamer

In this post we are going to make a simple exercise to show how quickly you can integrate Lightstreamer with Ember.js, a popular JavaScript MVC framework aimed at making easier the development of so-called Single Page Applications.






Let's start by delving into the code example.

The Application Code

As required by every Ember application, we first need to create a new instance of the Application class:

Then, we define the "stock" resource, mapped to the index "/" of our application:

Now it is time to create a model class to describe a Stock Item, in which all attributes map to the field schema specified in the subscription request, as will be shown later on:

As a simple and fast way to persist our data, we decide to lean on the local-storage adapter, a third-party Ember Adapter which stores the object instances into the browser's local database. To do that, let's initialize the ApplicationAdapter:

The StockRoute class is the core of the example. In the snippet below the complete implementation:

In the activate hook we make the real integration between Ligthstreamer and Ember.js happen. As you can see, the onItemUpdate callback manages the update of the model that backs the template (as will be defined in the next section). Once a new item event comes from the server, a find from the store is executed to lookup the matching object, in order to update its attribute values according to the modified item fields.
Finally, in the model hook we simply return all the objects retrieved from the local storage, by invoking  the store's findAll method. In this way, each change to an object performed in the onItempUpdate function will be automatically reflected by the framework in the HTML page.

The HTML Code

In order to display the real-time data updates flowing in from the server, we need to define a template:

In the above snippet, we iterate through the model provided by the StockRoute class defined above and, for each item, a new row table is rendered providing in each cell the corresponding attribute value.

The full code example is available on Github:
https://github.com/Lightstreamer/Lightstreamer-example-StockList-client-ember

And here you can see the final live result.




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.