Over a million developers have joined DZone.

Knockout.js Client for Java EE RESTful Web Service

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Once a RESTful web service has been published, multiple approaches can be taken to consume the data exposed by the service. Let's take Knockout as a JavaScript framework for consuming a RESTful web service.

Here's all that's needed, in a file named 'app.js', to consume a RESTful web service via Knockout. In this case, the RESTful web service provides a 'name' and a 'city' which, below, via declarative UI bindings are made available to the view:

MyCustomerViewModel = function() {
    var self = this;
    self.customers = ko.observableArray();
    $.getJSON("http://localhost:12345/CustomerManager/webresources/customers").
        then(function(customers) {
            $.each(customers, function() {
                self.customers.push({
                    name: ko.observable(this.name),
                    city: ko.observable(this.city)
                });
            });
        });
};
ko.applyBindings(new MyCustomerViewModel());

Related reading:

And here's the view, notice the 'data-bind' attributes that connect the view to the JavaScript file above.

<html>
    <head>
        <title>Customer Data</title>
    </head>
    <body>
        <table border="1">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>City</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: customers">
                <tr>
                    <td data-bind="text: name"/>
                    <td data-bind="text: city"/>
                </tr>
            </tbody>
        </table>
        <script src="js/libs/knockout/knockout-min.js" type="text/javascript"></script>
        <script src="js/libs/jquery/jquery.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>
    </body>
</html>

Finally, below, you see the working environment for creating the application described above, together with the result in the embedded browser of NetBeans IDE. Click to enlarge the image.

How to automate this process is described here: Knockout Client Generator for RESTful Web Services 

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}