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 ROUTING• Tip This listing requires the HTML5 History API, and unlike the earlier examples in this chapter, there is nofallback to the HTML4-compatible approach taken by the Hasher library.I create an object that has a category property that contains the name of the selected category andone property <strong>for</strong> each individual cheese that has a nonzero quantity value. I write this to the browserhistory using the replaceState method, which I have highlighted in the listing.Something clever is happening here. To explain what I am doing—and why—we have to start withthe markup <strong>for</strong> the navigation elements that remove products from the basket. Here is the relevantHTML:When the data bindings are applied, I end up with an element like this:In Chapter 3, I removed items from the basket by handling the click event from these elements.Now that I am using URL routing, I have to define a route, which I do like this:crossroads.addRoute("remove/{id}", function(id) {map<strong>Pro</strong>ducts(function(item) {if (item.id == id) {item.quantity(0);}}, cheeseModel.products, "items");});My route matches any two-segment URL where the first segment is remove. I use the secondsegment to find the right item in the view model and change the value of the quantity property to zero.At this point, I have a problem. I have navigated to a URL that I don’t want the user to be able tonavigate back to because it will match the route that just removes items from the basket, and thatdoesn’t help me.The solution is in the call to the history.replaceState method. When the quantity value is changed,my subscription causes the updateState function to be called, which in turn calls history.replaceState.The third argument is the important one:history.replaceState(state, "", "#select/" + cheeseModel.selectedCategory());The URL specified by this argument is used to replace the URL that the user navigated to. Thebrowser doesn’t navigate to the URL when it is changed, but when the user moves back through thebrowser history, it is the replacement URL that will be used by the browser. Irrespective of which routematches the URL, the history will always contain one that starts with #select/. In this way, I can use URLrouting without exposing the inner workings of my web app to the user.107www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!