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

Refactoring 537

access XML feeds from any site without having to open multiple tabs or windows by using this reader. We also have the ability to alter this application to obtain other information from the Web, such as weather and comics.

13.6.2Changing the application scope

This application is not limited to being an XML syndication reader from sites. We can easily adapt it as a banner ad rotator, company news updater, an event calendar, and so much more.

For instance, we can store our banner ads within an XML document. That way, anyone can update the XML file with new ads without having to touch any of the HTML files or the server-side code. We can preload the banner ads and have them displayed in the reader. Instead of just having one ad on the screen, we can have them rotate through as the user is reading the site.

We can set up the XML document to hold the company news so we can display our current articles to the employees or customers. We just need to fill in the basic items of the XML feed. We can also make it display the updates to the site or any other information we want. As you can see, we are not limited to just the plain XML feeds.

13.7Refactoring

Now that we have a fully developed script for reading RSS feeds, let’s take the time once again to improve upon our efforts. As mentioned earlier, there are lots of possibilities for extending our script in terms of perusing different types of content. In this section, we concentrate on reorganizing the script along Model- View-Controller (MVC) boundaries. As we explained in chapters 3 and 4, the MVC pattern is a very common design pattern for separating the responsibilities of software. We’ll start our discussion with defining the Model types, then we’ll create a View for the Model, and finally we’ll round out the discussion with the Controller that ties everything together.

13.7.1RSS reader Model

The RSS reader we’ve developed in this example will definitely benefit from having some first-class Model types to deal with. This will make the software conceptually cleaner and easier to read and maintain. With Ajax-based applications putting a heavier emphasis on the client DHTML than more traditional web applications, it becomes increasingly important to write clean, maintainable software. The Model classes we develop should also be generally applicable to other

538CHAPTER 13

Building stand-alone applications with Ajax

applications that deal with RSS feeds. As a syntactic simplification, we’ll use the Prototype library to define types just as we did in chapter 10.

Let’s start by defining a Model class for an RSS feed. An RSS feed is for our purposes an XML document that adheres to a predefined structure and has a URL that specifies how it can be accessed. The primary attributes of the structure are the title, link, and description, with many other optional attributes, as discussed earlier. The feed also has several items, which can be thought of as the articles of its content. Let’s start by capturing what we know so far, as represented in listing 13.21.

Listing 13.21 The RSSFeed Model class

RSSFeed = Class.create();

RSSFeed.prototype = {

initialize: function(

title, link, description ) {

this.title

=

title;

this.link

=

link;

this.description =

description;

this.items

=

[];

},

 

 

addItem: function(anItem) { this.items.push(anItem);

}

};

This code defines the RSSFeed type via the Prototype library Class.create(). You will recall that using this idiom, the initialize method is invoked by the generated constructor. So with this definition of our RSS feed Model class, a feed could be constructed via the following line of code:

var rssFeed = new RSSFeed( 'JavaRanch News', 'http://radio.javaranch.com/news/', 'Stories from around the ranch' );

This is pretty much all that’s required for the definition of an RSSFeed Model object. Notice that the RSSFeed has an addItem API that enables the addition of items to the internal item’s array. Each item should be a Model object as well— one that encapsulates the attributes of each item in the feed. Given what we know about the RSS items, let’s define our item Model class as shown in listing 13.22.

Refactoring 539

Listing 13.22 The RSSItem Model class

RSSItem = Class.create();

RSSItem.prototype = {

initialize: function(

rssFeed, title, link, description ) {

this.rssFeed

=

rssFeed;

this.title

=

title;

this.link

=

link;

this.description =

description;

}

 

 

};

Nothing much to get excited about here. The item encapsulates the title, link, and description attributes but also holds a reference to the RSSFeed object that it belongs to. Given these two Model classes, now we can envision that an item and one of its feeds could be constructed as shown here:

var rssFeed = new RSSFeed( 'JavaRanch News',

'http://radio.javaranch.com/news/', 'Stories from around the ranch' );

var feed1 = new RSSItem( rssFeed, 'Win a copy of JBoss',

'http://radio.javaranch.com/news/05/07/20/9.html', 'Text of Article' );

rssFeed.addItem(feed1);

So far, so good. The Model is a very straightforward encapsulation of the attributes of an RSS feed and its items. The two Model classes that encapsulate these two concepts are RSSFeed and RSSItem, respectively. Now let’s consider the construction of the Model itself. We know that these objects will get instantiated as a result of the XML data being loaded into the client by an Ajax request. So let’s define an API that our Ajax handler can call for converting the XML response into an instance of our RSSFeed Model class. Let’s start by defining the contract of our Model creator as follows:

var rssFeed = RSSFeed.parseXML( rssXML );

This contract implies that we’ll pass the XML response returned from our Ajax handler to the parse method of our RSSFeed type, and it will return to us an instance of an RSSFeed. Given that assumption, let’s implement the parseXML() method as shown in listing 13.23.

540CHAPTER 13

Building stand-alone applications with Ajax

Listing 13.23 The RSS XML parsing

RSSFeed.parseXML = function(xmlDoc) {

var rssFeed = new RSSFeed( RSSFeed.getFirstValue(xmlDoc, 'title'), RSSFeed.getFirstValue(xmlDoc, 'link' ), RSSFeed.getFirstValue(xmlDoc, 'description'));

var feedItems = xmlDoc.getElementsByTagName('item'); for ( var i = 0 ; i < feedItems.length ; i++ ) {

rssFeed.addItem(new RSSItem(rssFeed, RSSFeed.getFirstValue(feedItems[i], 'title'), RSSFeed.getFirstValue(feedItems[i], 'link' ), RSSFeed.getFirstValue(feedItems[i], 'description'))

}

return rssFeed;

}

This method does the textbook response XML parsing that we’ve done many times already. It takes the values of the title, link, and description elements and uses them to create the RSSFeed. It then iterates over all of the item elements and does the same, creating an RSSItem instance for each. Within each iteration, the addItem() method is used to add the item to its parent RSS feed. Note that a helper method is used here to get the node value from the first child of an element with a given tag name. The helper method, getFirstValue, is shown in listing 13.24.

Listing 13.24 Parsing helper method

RSSFeed.getFirstValue = function(element, tagName) {

var children = element.getElementsByTagName(tagName); if ( children == null || children.length == 0 )

return "";

if ( children[0].firstChild && children[0].firstChild.nodeValue )

return children[0].firstChild.nodeValue; return "";

}

This is everything we need from a Model perspective. Obviously, we could add attributes for all the optional parts of an RSS feed and populate them if they are present in the feed. We didn’t do that in this case because the RSS reader doesn’t use or need any of the optional attributes. But it’s definitely an opportunity to