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 ROUTINGApplying URL RoutingI have almost everything in place: a set of navigational controls and a set of content elements. I nowneed to tie them together, which I do by applying the URL routing:var 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/Apple", function() {viewModel.selectedItem("Apple");});crossroads.addRoute("select/Orange", function() {viewModel.selectedItem("Orange");});crossroads.addRoute("select/Banana", function() {viewModel.selectedItem("Banana");});});The first three of the highlighted statements set up the Hasher library so that it works withCrossroads. Hasher responds to the internal URL change through the location.hash browser object andnotifies Crossroads when there is a change.Crossroads examines the new URL and compares it to each of the routes it has been given. Routesare defined using the addRoute method. The first argument to this method is the URL we are interestedin, and the second argument is a function to execute if the user has navigated to that URL. So, <strong>for</strong>example, if the user navigates to #select/Apple, then the function that sets the selectedItem observablein the view model to Apple will be executed.• Tip We don’t have to specify the # character when using the addRoute method because Hasher removes itbe<strong>for</strong>e notifying Crossroads of a change.In the example, I have defined three routes, each of which corresponds to one of the URLs that Icreated using the <strong>for</strong>matAttr binding on the a elements.83www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!