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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 4 USING URL ROUTINGThe second is much more interesting. Data bindings are not the means by which view modelchanges are propagated into the web app. You can also subscribe to an observable data item and specifya function that will be executed when the value changes. Here is the subscription I created:map<strong>Pro</strong>ducts(function(item) {item.quantity = ko.observable(0);item.subtotal = ko.computed(function() {return this.quantity() * this.price;}, item);item.quantity.subscribe(function() {updateState();});}, cheeseModel.products, "items");I subscribed to the quantity observable on each cheese product. When the value changes, theupdateState function will be executed. I’ll describe this function shortly. Subscriptions are rather likeevents <strong>for</strong> the view model; they can be useful in any number of situations, and I often find myself usingthem when I want some task per<strong>for</strong>med automatically.Managing Application StateI want to preserve two kinds of state in this web app. The first is the selected product category, and thesecond is the contents of the basket. I store state in<strong>for</strong>mation in the browser’s history in the updateStatefunction, which is executed whenever my quantity subscription is triggered or the selected categorychanges.• Tip The technique that I demonstrate here is a little odd when applied to a shopping basket, because web siteswill usually go to great lengths to preserve your product selections. Ignore this, if you will, and focus on the statemanagement technique, which is the real purpose of this section.function updateState() {var state = {category: cheeseModel.selectedCategory()};map<strong>Pro</strong>ducts(function(item) {if (item.quantity() > 0) {state[item.id] = item.quantity();}}, cheeseModel.products, "items");history.replaceState(state, "", "#select/" + cheeseModel.selectedCategory());}106www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!