12.07.2015 Views

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

Pro JavaScript for Web Apps pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 3 ADDING A VIEW MODELAdopting a View Model LibraryFollowing the principle of not writing what is available in a good <strong>JavaScript</strong> library, I will introduce aview model into the web app using a view model library. The one I’ll be using is called Knockout (KO). Ilike the KO approach to application structure, and the main programmer <strong>for</strong> KO is Steve Sanderson, whois my coauthor <strong>for</strong> the <strong>Pro</strong> ASP.NET MVC book from Apress and an all-around nice guy. To get KO, go tohttp://knockoutjs.com and click the <strong>Download</strong> link. Select the most recent version (which is 2.0.0 as Iwrite this) from the list of files and copy it to the Node.js content directory.• Tip Don’t worry if you don’t get on with KO. Other structure libraries are available. The main competition comesfrom Backbone (http://documentcloud.github.com/backbone) and AngularJS (http://angularjs.org). Theimplementation details in these alternative libraries may differ, but the underlying principles remain the same.In the sections that follow, I will bring my view model and the view model library together todecouple parts of the example application.Generating Content from the View ModelTo begin, I am going to use the data to generate elements in the document so that I can display theproducts to the user. This is a simple use of the view model, but it reproduces the basic functionality ofthe implementation in Chapter 2 and gives me a good foundation <strong>for</strong> the rest of the chapter. Listing 3-3shows the addition of the KO library to the document and the generation of the elements from the data.Listing 3-3. Generating Elements from the View ModelCheeseLuxvar cheeseModel = {category: "French Cheese",items: [ {id: "camembert", name: "Camembert", price: 18},{id: "tomme", name: "Tomme de Savoie", price: 19},{id: "morbier", name: "Morbier", price: 9}]};$(document).ready(function() {49www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!