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 ROUTINGAdding the Navigation MarkupI generate a set of a elements to provide the user with the means to select different items; in my simpleapplication, these <strong>for</strong>m the navigation markup. Here is the markup:As I mentioned in Chapter 3, the built-in KO bindings simply insert values into the markup. Most ofthe time, this can be worked around by adding span or div elements to provide structure to whichbindings can be attached. This approach doesn’t work when it comes to attribute values, which is aproblem when using URL routing. What I want is a series of a elements whose href attribute contains avalue from the view model, like this:AppleI can’t get the result I want from the standard attr binding, so I have created another custom one.Listing 4-3 shows the definition of the <strong>for</strong>matAttr binding. I’ll be using this binding later, so I havedefined it in the util.js file, alongside the fadeVisible binding.Listing 4-3. Defining the <strong>for</strong>matAttr Custom Bindingfunction composeString(bindingConfig ) {var result = bindingConfig.value;if (bindingConfig.prefix) { result = bindingConfig.prefix + result; }if (bindingConfig.suffix) { result += bindingConfig.suffix;}return result;}ko.bindingHandlers.<strong>for</strong>matAttr = {init: function(element, accessor) {$(element).attr(accessor().attr, composeString(accessor()));},update: function(element, accessor) {$(element).attr(accessor().attr, composeString(accessor()));}}The functionality of this binding comes through the accessor. The binding argument I have used onthe element is a <strong>JavaScript</strong> object, which becomes obvious with some judicious re<strong>for</strong>matting:<strong>for</strong>matAttr:{attr: 'href',prefix: '#select/',value: $data},css: {selectedItem: ($data == viewModel.selectedItem())}KO resolves the data values be<strong>for</strong>e passing this object to my init or update methods, giving mesomething like this:81www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!