Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ajax In Action (2006).pdf
Скачиваний:
63
Добавлен:
17.08.2013
Размер:
8.36 Mб
Скачать

496CHAPTER 12

Live search using XSLT

The specific update implementations, whether IE or Mozilla, perform two basic steps: b performing the XSLT transformation, and c updating the UI with the result. Recall that the result of the Mozilla transformation process is a document fragment that is added to an element via appendChild(), whereas the IE transformation results in a string that is added via the innerHTML property. So with that in mind, the updateViewIE() implementation is shown here:

updateViewIE: function() { this.container.innerHTML =

this.xmlDocument.transformNode(this.xslStyleSheet);

},

The same two steps are performed in the IE implementation, which is a good deal more compact because the steps of applying the transformation and updating the UI are all done in a single line of code. As to which one is more efficient, we’ll let you decide.

Our XSLTHelper is now complete, and we have a clean, simple, one-method API for performing XSLT transformations. Our helper should prove to be very useful and more than worth the relatively small amount of effort we have put into it. Now let’s refocus our efforts on the live search and contemplate a simple component design.

12.6.2A live search component

Now that we have some sweet XSLT help in our back pocket, let’s implement our live search script as a component that uses it. The component should satisfy the component requirements that we’ve discussed in detail in our other refactoring examples. These include such things as providing a clean API, being configurable while providing appropriate default values, being unobtrusive to the surrounding HTML, and being able to have multiple instantiations on a page. Let’s develop a clean object-oriented solution with the guiding principle that each responsibility should be encapsulated in a dedicated method. One responsibility, one method. With that in mind, let’s get started in the usual place—considering construction.

From the perspective of component state, the live search component has to keep track of more “stuff ” than most other components we’ve written. It needs to know about an XML document source, an XSL document source, a field that initiates the search, and the URL of the page that it should use to support bookmarking. So, that means our constructor is going to be a little heavier in this example than in previous ones. However, it should still be quite manageable. Let’s take a stab at a live search constructor now:

Refactoring 497

function LiveSearch(

pageURL, lookupField, xmlURL,

xsltURL, options ) {

 

this.pageURL

= pageURL;

this.lookupField

= lookupField;

this.xmlURL

= xmlURL;

this.xsltURL

= xsltURL;

this.setOptions(options); b Configure the component

var oThis = this; lookupField.form.onsubmit = function(){

oThis.doSearch(); return false; };

this.initialize();

 

Go to previous search

 

}

 

 

The first four arguments of our constructor are the things we just indicated we’d have to keep up with: the URL of the page, the search field, and the two document URLs. The last parameter is our familiar options parameter for providing component configurability. The options argument is passed to the setOptions() method, which, as you recall, provides some default values for all configurable data b. Let’s look briefly at the defaults before moving on:

setOptions: function(options) { this.options = options;

if ( !this.options.loadingImage ) this.options.loadingImage = 'images/loading.gif';

if ( !this.options.bookmarkContainerId ) this.options.bookmarkContainerId = 'bookmark';

if ( !this.options.resultsContainerId ) this.options.resultsContainerId = 'results';

if ( !this.options.bookmarkText ) this.options.bookmarkText = 'Bookmark Search';

},

The setOptions() method is not as succinct as its counterpart in the TextSuggest component (see chapter 10), which used the Prototype library’s extend() method to make the expression of this nice and compact. This method performs the same chores, however, and provides default values for the loading image, the ID of the element to contain the bookmark, the ID of the element to contain the result data, and, finally, the text of the generated bookmark. Recapping the mechanism, any values to these properties that live in the options object passed in by the user will override the defaults that are specified here. The resulting options object is a merged set of defaults and their overrides in a single object. These options are then used at the appropriate points throughout the rest of the example to configure the component.

498CHAPTER 12

Live search using XSLT

With component configurability and defaults squared away, let’s turn our attention back to the constructor for a moment and recall these two unassuming lines of code:

var oThis = this; lookupField.form.onsubmit = function(){

oThis.doSearch(); return false; };

You will recall that our script in its original form modified the HTML by putting an onsubmit handler on the search form:

<form name="Form1" onsubmit="GrabNumber();return false;">

Because we are striving to make our components as unobtrusive as possible, at least in terms of the amount of HTML that needs to be modified to use them, the same functionality has been provided by these two aforementioned lines of our constructor. The difference from a naming point of view is that we’ve renamed GrabNumber() to a more generic name, doSearch(), and doSearch() is a method of our component rather than a global function. Speaking of which, let’s now take a look at the doSearch() method implementation:

doSearch: function() {

if ( XSLTHelper.isXSLTSupported() ) this.doAjaxSearch();

else this.submitTheForm();

},

Our smarty-pants component knows that it should be checking for XSLT support before trying to actually do XSLT processing, so the search method uses the XSLTHelper API we wrote earlier to determine whether to use XSLT processing or to just do a standard form submission. Pretty smart indeed. Our client can just call the doSearch() method and not have to worry about whether it’s doing XSLT. We’ve taken care of all the worrying for it. Let’s take each of the two forms of searching and look at them in detail. Because the form submission is simpler, we’ll look at it first:

submitTheForm: function() {

var searchForm = this.lookupField.form; searchForm.onsubmit = function() { return true; }; searchForm.submit();

},

This method simply finds the reference to the appropriate form through the lookup field and changes its onsubmit to a function that returns true. This allows the search request to be submitted back to the server in an explicit way. Then the

Refactoring 499

method just calls the submit() method of the native HTML form, which causes a traditional form submission. In this scenario, the component assumes that there is an appropriate action attribute of the form and that the result of the action returns an appropriate page with search results.

Now let’s look at the Ajax implementation of searching:

doAjaxSearch: function() {

 

 

this.showLoadingImage();

b Show loading image

var searchUrl = this.appendToUrl( this.xmlURL,

'q',

 

c Formulate URL

this.lookupField.value);

new XSLTHelper(searchUrl,

d Perform XSLT processing

this.xsltURL).loadView( this.options.resultsContainerId);

this.updateBookmark ();

e Update bookmark

},

 

The doAjaxSearch() method performs the same steps that the first iteration of our script did, but it puts each step into a method to perform each responsibility. At this point, you might object and say that this method has four responsibilities. Well, actually it just has one: searching. However, the responsibility of searching has four parts, each a responsibility on its own. So let’s look at each in turn:

bShow the loading image—The search is started by calling the method to show the “busy loading” image. The image used is determined by the options object:

showLoadingImage: function() {

var newImg = document.createElement('img'); newImg.setAttribute('src', this.options.loadingImage ); document.getElementById( this.options.resultsContainerId).appendChild(newImg);

},

cFormulate the search URLThe search URL is built using the xmlURL attribute that was passed in at construction time with a q= parameter appended to it with the value currently contained in the lookup field. The appending is performed by a method that checks the URL for the existence of a previous querystring to make sure the correct parameter separators are used:

appendToUrl: function(url, name, value) {

var separator = '?';

if (url.indexOf(separator) > 0; ) separator = '&';

return url + separator + name + '=' + value;

},

500CHAPTER 12

Live search using XSLT

dDo the XSLT processing and update the UIBecause we had the presence of mind to factor out the task of client-side XSLT processing, this seemingly heavy-duty responsibility is achieved within a single line of code:

new XSLTHelper(searchUrl, this.xsltURL).loadView(this.options.resultsContainerId);

eUpdate the bookmark—Once the user has initiated a search, the bookmark should be updated as well. This responsibility is performed via the updateBookmark() method:

updateBookmark: function() {

var container = document.getElementById( this.options.bookmarkContainerId);

var bookmarkURL = this.appendToUrl( this.pageURL, 'q', this.lookupField.value );

if ( container )

container.innerHTML = '<a href="' + bookmarkURL + '" >' + this.options.bookmarkText + '</a>';

}

This method gets the container element and the text for the bookmark from the options object. The URL for the generated bookmark is the value passed into the constructor as the pageURL argument. The q= parameter with the value of the current search are appended to that URL. The innerHTML property of the container is updated with all of these values to produce the appropriate URL.

If a bookmark is stored and used to hit our page, the user is returned to our page with a q=someValue parameter. But what initiates the search to produce the result? Recall that the final line of the constructor called this.initialize();. We’ve not peeked at what that actually does yet, so we should do so now. As you’ve probably guessed, the initialize() method is there to support our bookmarking feature. The implementation is as follows:

initialize: function() {

var currentQuery = document.location.search; var qIndex = currentQuery.indexOf('q=');

if ( qIndex != -1 ) { this.lookupField.value =

currentQuery.substring( qIndex + 2 ); this.doSearch();

}

},