Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Knockout.js Client for Java EE RESTful Web Service

DZone's Guide to

Knockout.js Client for Java EE RESTful Web Service

· Java Zone ·
Free Resource

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

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 

Use this tool to look at the contents of GitHub and classify code based on the programming language used.  Content provided by IBM Developer.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}