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 9 WRITING BETTER JAVASCRIPTcat: "British"};var testElem = $("").attr("data-bind","<strong>for</strong>matAttr: {attr: 'href', prefix: '#', value: cat}")[0];ko.applyBindings(viewModel, testElem);equal(testElem.attributes.length, 2);equal($(testElem).attr("href"), "#British");});});});AMD Teststest markup, will be hiddenI have added a new test that uses jQuery to create an a element and apply a data-bind attribute. Ifyou pass an HTML fragment to the jQuery $ shorthand function, the result is a DOM API element that isnot attached to the document. As a bonus, I don’t have to make sure that the single and double quotes inthe data-bind attribute are properly escaped when using the jQuery attr method:var testElem = $("").attr("data-bind","<strong>for</strong>matAttr: {attr: 'href', prefix: '#', value: cat}")[0];Notice that I used an array-style indexer to get the first element in the object returned by the jQuery$ shorthand function. The ko.applyBindings method works on the DOM API object rather than jQueryobjects and so I need to unwrap the a element I have created from the jQuery object. At this point, I canget Knockout.js to apply bindings to my HTML fragment using my test view model:ko.applyBindings(viewModel, testElem);To test the result, I use the QUnit equal function and both the DOM API and jQuery to inspect theresult:equal(testElem.attributes.length, 2);equal($(testElem).attr("href"), "#British");jQuery makes it easy to create and prepare HTML <strong>for</strong> testing and check the results, and as thisexample shows, you can use the DOM API to get in<strong>for</strong>mation about the elements after the test hascompleted. As you can see, jQuery and QUnit together make testing every aspect of a web app possibleand, <strong>for</strong> the most part, easy to do.258www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!