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 ROUTINGSo that I can respond appropriately to the URL, the content of the variable segment is passed to myfunction as an argument. I use this argument to change the value of the selectedItem observable in theview model, meaning that a URL of /select/Apple results in a call like this:viewModel.selectedItem('Apple');and a URL of select/Cherry will result in a call like this:viewModel.selectedItem('Cherry');Dealing with Unexpected Segment ValuesThat last URL is a problem. There isn’t an item called Cherry in my web app, and setting the view modelobservable to this value will create an odd effect <strong>for</strong> the user, as shown in Figure 4-3.Figure 4-3. The result of an unexpected variable segment valueThe flexibility that comes with URL routing can also be a problem. Being able to navigate to aspecific part of the application is a useful tool <strong>for</strong> the user, but, as with all opportunities <strong>for</strong> the user toprovide input, we have to guard against unexpected values. For my example application, the simplestway to validate variable segment values is to check the contents of the array in the view model, as shownin Listing 4-5.Listing 4-5. Ignoring Unexpected Segment Values...crossroads.addRoute("select/{item}", function(item) {if (viewModel.items.indexOf(item) > -1) {viewModel.selectedItem(item);}});...In this listing, I have taken the path of least resistance, which is to simply ignore unexpected values.There are lots of alternative approaches. I could have displayed an error message or, as Listing 4-6shows, embraced the unexpected value and added it to the view model.86www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!