Your own sports news site with ESPN API and Knockout.js

I was really excited when I heard the announcement of the ESPN API. Being a sports freak like me, that opens a tremendous amount of possibilities for application development. Today, let’s build our own sports news single-page application, fueled entirely by Knockout.js.

You will be able to browse the latest news from ESPN from all sports categories, as well as filter them by tags. The UI will be powered by KnockoutJS and Twitter bootstrap, and yes, will be a single page. We have already done two projects together using knockout.js – API infinite scroll and ASP.NET WebAPI file upload. Hopefully we will continue our knockout.js adventures in an exciting, and interesting for you, way.

More after the jump.

ESPN API overview

You can find out more about ESPN API here. You will have to generate your own API key to use the API. Unfortunately, in the public portion of the API, only calls to news (headlines) and news categories are allowed. Additionally, the public API key allows only for 1 call per second and 2500 calls per day. If you want to have access to teams, players and more, or expect high volume transactions, or simply intend to use the API for commercial purposes, you’d have to reach an agreement with ESPN to become its approved partner.

Anyway, let’s get rolling.

Our UI

For rapid development, we will use Twitter boostrap to glue our UI. Here is what our application is going to look like (hopefully…) after we go through all development steps.

Remember this is going to be a single page application, so a lot will be happening to the UI.
You will have a menu on the left, listing all news categories. The main area (right column) will be the list of all the news. News items will be loaded in batches of 10. On the top, you will have a indicator of how many news items are being shown, and how many are available in the given category. Similarly, the same information will be available below the news section, only in the form of a progress bar (one of the functionalities perfect for Knockout.js).

Additionally, each news will display a set of tags, clicking on a tag, will filter the current news list based on a given tag.

starting off with Javascript code

We start off by defining an object containing all news categories available via the API. Surprisingly, ESPN API doesn’t provide a method to retrieve such collection, so we need to code it in manually.

Next step is to define the viewModel. If you are accustomed to knockout.js, there should be no surprises. A note here is that we will have to have nested observables to facilitate our needs.

Let’s go through all the properties:
– headlines – the observable array that will contain our news items
– totalHeadlines – total amount of news items available in the category (remember, we will be loading in batches, so we won’t load all headlines at once)
– categories – this is just our categories list we set up manually, added to viewModel for convenience
– selectedTag and its nested observables – if the user filters by a tag, we will store the tag name there, as well as keep track of how many news items have been fitlered out
– selectedCat – if the user selects a category, we will story the category name and url there

These are all the properties of the viewModel. Additionally, we will need 3 viewModel methods, and 1 computed observable. I declare the separately, since the {} bracket syntax to declare JS objects doesn’t support declaring properties and methods utilizing those properties in one go.

First, let’s look at the computed observable, storyProgress:

Since it is a computed property, it’s value depends on other observables. If there are any headlines loaded, and if the total number of headlines available is greater then 0, we return a percentage value of how many of the available stories have been loaded into the headlines array. We will use that to fuel the progress bar I mentioned earlier.

Next thing is the method which will load the actual headlines into the headlines array. Let’s have a look at it.

We will be calling this method from the click event on the categories list, so we will be passing to it a data object which will be one of the objects from the previously created “headlines_list” (or, if you followed the text closely, actually the viewModel.catgories).

So whenever this method is called, we set the selectedCat to appropriate values, call the flushCategory helper method (to clear existing headlines and tags) and then query the ESPN API.

Category flushing comes down to removing all object from the headlines array and resetting the selectedTag back to default state. We will get to querying the API a bit later. For now, let’s have a look at the remaining two viewModel methods.

The load_more method is called when the user wants to load the next batch of the headlines. First we need to flush the tag filtering (since the new batch will come unfiltered), then we just call the API again, but this time passing the results_offset parameter, which basically tells the API, ok we have n news items already, give me 10 more, starting from item n+1.

Finally, the last viewModel method is responsible for filtering by Tags.

This method will be called whenever the user clicks on the tag below each story. We introduce a new parameter, value, which will be passing the actual text value of the clicked element. This is necessary, since the data item is not good enough in this case( as it was for the category loading, since knockout js context item is not the Tag item, but the story item, so data contains the story item (if it doesn’t make sense, don’t worry, we’ll get back to this when we inspect our knockout.js data bindings).

The principle in Tag filtering is that, we take the tag value, iterate through all headlines, and then through all “categories” of the headline (this is how ESPN API named what we use as “tags”). If we find a match (= story has the tag we are filtering by) we exit the loop and nothing happens. If there is no match, we hide the headline, by setting its “show” observable property to false and increment the “hidden” property (which is our hidden stories counter) of viewModel.selectedTag.

For the record, let’s see what flushTagFilter method does:

Basically, it sets all headlines back to “show” status, and clears the viewModel.selectedTag.

OK, finally, what we need to do is apply the bindings. If no category is selected (=user just arrived on the page), load the default category, which in our case are “All ESPN stories”.

Querying the ESPN API and handling response

Now that we discussed the vieModel in detail, what we need to look at is querying the API itself. If you recall, we have encountered two calls to the API in the viewModel code, in the category_load and load_more methods.

Let’s inspect the call:

The call is a pretty simple wrapper around jQuery’s AJAX GET request. We pass the category URL, which we use to build up the HTTP url, we also pass our unique API key, request limit and offset. We also define two handlers, for response and error.

Let’s look at success handler:

We set the totalHeadlines property of the viewModel based on the result returned from API. Additionally, we iterate through the responses and push each headline (news item) into the headlines observable array. Before doing that, we add a boolean observable property to each headline, which we will be used for showing/hiding the story upon tag filtering (recall please the filterByTag method from earlier).

Error handler is rather self explanatory:

That’s almost everything, we just need a few helper handler for the UI:

They don’t do anything exciting, just add/remove CSS classes of highligthed items, or allow user to close the error box.

Off to HTML

Now that we have all Javascript in place, let’s shift our attention to the HTML. First we need to include all the libraries we will be relying on – and there is quite a few of them:
– jQuery
– Knockout.js
– jQuery tmpl (we’ll use that instead of native knockout templates)
– all the Twitter Boostrap extravaganza

So here is all our javascript, placed at the end of the document:

Additionally, we will load the default boostrap.css and a bit of our own custom javascript

Data bindings

The final piece of puzzle is to write the HTML that will be bound to our viewModel and display everything as we wish.
I will not go into details of the Twitter Boostrap naming conventions and classes, you can see that yourself in the attached source code or simply at Boostrap site.
Instead, I will just focus on the actual bindings and how knockout.js will interact with the page, as I think this is much more interesting. Let’s just say that our site will be split into two columns, one span3 and one span9 and will be contained within a div row-fluid, to stretch 100% width.

Categories list
Categories list contains clickable news sections.

For simplicity, we use two separate ul-s (not the ebst practice). Since Twitter Boostrap uses 1st li as a header, I want to avoid having to inject a dummy item on top of the categories list binding. Categories list is bound to the categoriesTemplate, and iterates through viewModel.categories.

Categories template displayes category name, and upon clicking calles the category_load method. The data bound item is passed to the method as data object, which was explained earlier when we discussed the category_load method.

Content pane
Content column consists of three sections:
– top: where we display category name, item count and current tag used for filtering
– middle: where we display headline items + tags relevant for each
– bottom: where we display progress bar and “load more” button

1. Top section:

So we bind page title to property. We display information of how many items are shown by substracting the items hidden by tag filtering (so without filtering, 0) from the total number of headlines loaded. Additionally we display and information of how many total headlines are available.

We also add a binding for tag filtering indicator. It’s visibility is tied to the fact if property is set or not. If it’s not, nothing is shown, if it is, then we display the property.

2. Middle area, where the headlines are displayed

The binding is super simply, just binding to the headlines observable array. More interesting stuff in the template that’s used there:

First we wrap everything in an {{if show}} condition, meaning that if the property of headline object is false, nothing is displayed. This is our tag filtering prerequisite. the we display the new story “headline” propert (= title), link to ESPN and the description. Then we also show the story type and published date. Finally we display the tags (again, confusing enough since ESPN API calls them “categories”). We loop through all categories (=tags) using {{each}} and we add a click handler to each tag, binding it to filterByTag method. As mentioned, due to a shift in context, data parameter is still the parent (headline), we need to manually pass the value of the tag by using $value.description.

3. Bottom section
Finally, at the bottom sits the stories progress bar (which will tell the user how many out of all the stories have been loaded) and a a button to load more.

The progress bar is a Twitter Boostrap functionality, all we need to pass to it is the percentage value, which we generate using our computed property of the viewModel, sttoryProgress. And the “load more” button is just bound to viewModel.load_more event.

Tryin it out

So now that everything is in place, all that’s left to do is to try the web application out. This is how it should look after you load:

Clicking on any category, loads that category – i.e. NHL

Filtering by tag:

Notice how nicely the progress bat reacts to all changes in the headlines array:

Source code and demo

As usually, you can download the source code. Please remember to generate your own API key and insert it in the the queryESPNAPI method of the code! Otherwise the source code will not work. you can generate your API key here.

Additionally, please note that the demo may not work perfectly fine under heavy load – remember that public ESPN API key allows for only 1 call per second and 2500 calls per day.
source files (650 KB, zip)
live demo

Thanks guys & gals, till next time.