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 4 USING URL ROUTINGConsolidating RoutesIn the previous example, I defined each route and the function it executed separately. If this were theonly way to define routes, a complex web app would end up with a morass of routes and functions, andthere would be no advantage over regular event handling. Fortunately, URLs routing is very flexible, andwe can consolidate our routes with ease. I describe the techniques available <strong>for</strong> this in the sections thatfollow.Using Variable SegmentsListing 4-4 shows how easy it is to consolidate the three routes from the earlier demonstration into asingle route.Listing 4-4. Consolidating Routesvar viewModel = {items: ["Apple", "Orange", "Banana"],selectedItem: ko.observable("Apple")};$(document).ready(function() {ko.applyBindings(viewModel);$('div.catSelectors').buttonset();hasher.initialized.add(crossroads.parse, crossroads);hasher.changed.add(crossroads.parse, crossroads);hasher.init();crossroads.addRoute("select/{item}", function(item) {viewModel.selectedItem(item);});});The path section of a URL is made up of segments. For example, the URL path select/Apple has twosegments, which are select and Apple. When I specify a route, like this:/select/Applethe route will match a URL only if both segments match exactly. In the listing, I have been able toconsolidate my routes by adding a variable segment. A variable segment allows a route to match a URLthat has any value <strong>for</strong> the corresponding segment. So, to be clear, all of the navigation URLs in thesimple web app will match my new route:select/Appleselect/Orangeselect/BananaThe first segment is still static, meaning that only URLs whose first segment is select will match, butI have essentially added a wildcard <strong>for</strong> the second segment.85www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!