X

Geertjan's Blog

  • June 3, 2015

Enterprise Web Development with Solid Knockout (Part 2)

Geertjan Wielenga
Product Manager

Let's now use Solid Knockout to access data from a database:

To get to the above point, I made relatively few changes and, most importantly, I made those changes within the modular framework that Solid Knockout provides. Below, the files in green are new, the files in blue are changed.

To get started, expose data from your database via RESTful Web Services, which is trivial to do in NetBeans IDE. Then use the Knockout Client Generator plugin to generate the skeleton client in your application. You should have the two files shown above in green, i.e., rename them and move them to the places where you see them above.

Now we're going to rewrite those files a bit to make them fit in with the Require.js-based enterprise structure provided by Solid Knockout.

Here's the rewritten "customers.js", which will point to a different RESTful Web Service endpoint for you:

define(['knockout','jquery'], function (ko) {
function CustomersModel() {
var self = this;
self.items = ko.observableArray();
$.getJSON("http://localhost:8080/mavenproject1/webresources/customers/").
then(function (customers) {
$.each(customers, function () {
self.items.push({
city: ko.observable(this.city),
phone: ko.observable(this.phone),
name: ko.observable(this.name),
addressline2: ko.observable(this.addressline2),
creditLimit: ko.observable(this.creditLimit),
addressline1: ko.observable(this.addressline1),
state: ko.observable(this.state),
fax: ko.observable(this.fax),
email: ko.observable(this.email),
});
});
});
}
return {
viewModel: CustomersModel,
template: {
require: 'text!templates/customers.tmpl.html'
}
};
});

And here's the rewritten "customers.tmpl.html":

<div class="container-fluid">
<table style="margin-top: 1.5cm" border="1">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Mail</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: name"/>
<td data-bind="text: city"/>
<td data-bind="text: email"/>
</tr>
</tbody>
</table>
</div>

Finally, in "initComponents.js", add your new component:

ko.components.register("customers", {require: 'js/modules/customers'});

And now, anywhere you want to see your customers, in your HTML view, e.g., in your "index.html", simply use it like this:

<div data-bind="component: {name: 'customers'}"></div>

Join the discussion

Comments ( 2 )
  • guest Thursday, June 4, 2015

    Good tutorial


  • King Wilder Thursday, July 30, 2015

    Very cool! I've been looking for something like this. I assume I can use this with any underlying data framework, like Microsoft's WebApi or the like?


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.