How to build a news aggregator with backbone.js - Part 1

In this post and the following, we will build a news aggregator in an unique page using backbone.js. By unique page, I mean that all user interactivities will be only in one HTML page, and backend server will provide only data and no HTML tags. Finally, fed by news, this application will use an API RESTful, http://newsinapp.io

backbone.js is a MVC framework in Javascript. A new quirk? A plaything for skilled developers? A fancy of a few gurus in javascript? I’m probably not the only person who thinks it. So I decided to look at it in hope of acquiring new knowledge. In fact, I’m often surprised with Javascript. I had been impressed with jQuery … Backbone.js is definitely another surprise. The kind of surprise that makes me say “I am old with my Python”. So the old man, he will keep his Python anyway, and he will get serious in Javascript.

Then, what is backbone.js ? This framework provides four features

  • Models as a class and key-values properties
  • Collections of models
  • Views which are populated and updated via events raised by models
  • All data could be synchronized with RESTful JSON interface. And, for me, this last feature is the most important.

To build this news aggregator, we are not going to implement a new RSS or ATOM parser, or implement a web crawler more efficient than Google (You have to wait the next post). In fact, we will use newsinapp.io API. It will provide news, and backbone.js will make life easier to display these news in a web page.

Actually in private alpha, http://newsinapp.io allows to define custom topics, and retrieve news about them. A topic is associated with a context to improve the quality/relevance of news. So, the “backbone.js“ topic will be associated with the “computers“ entity. And, the “Tim Burton“ topic will be associated with the “arts/movies“ entity.

Here, an example to retrieve the latest news

curl 'http://api.newsinapp.io/topics/news/v1/?auth_api_key=API Key'

And the JSON response:

{
   'topic':
   {
     'entities': [ 'arts' ],
     'displayName': 'tim burton',
     'id': '3144'
   },
   'relevanceRate': 1,
   'subTitle': 'New pic of Johnny Depp and Eva Green...',
   'title': 'New pic of Johnny Depp and Eva Green from Tim Burton''s Dark Shadows',
   'source': 'joblo.com',
   ...
}

Now, to begin with the end, here the backbone news aggregator URL that we will build in this article (and follow by others parts): Demo with backbone

Demonstration Screenshot

This web site contains an unique HTML page. Then, you don’t need to deploy a Django, node.js or others servers frameworks. You only need to put on your server: one web page and some CSS, javascripts files.

In short, everything starts with an index.html file. In this HTML, some javascripts have to be loaded:

<script src="javascripts/vendor/jquery.js"/>
<script src="javascripts/vendor/underscore.js"/>
<script src="javascripts/vendor/backbone.js"/>
<script src="javascripts/news.js"/>
  • jquery.js: If you want, you could avoid to use jquery, but it is inevitable for me !
  • underscore.js: A backbone.js dependency. I am too happy to re-discover map and filter functions as my old friend Python !
  • news.js: We will write all our custom javascript codes in this separate file.

Then, in this new.js file, some magic incantations are needed. Now, we will focus only on javascript code:

(function() {
    jQuery(function($) {
    // Where is my javascript code ?
    }); 
}).call(this);

Phew !

Now, we can write some lines of code using backbone.js.

First, we need to create the model to store each news:

window.NewsItem = Backbone.Model.extend({});

That’s all ? Interesting things begin when create the collection:

    window.NewsCollection = Backbone.Collection.extend({
        model: NewsItem,

public_api_key : 'A public api key from newsinapp.io’, url_base : 'http://api.newsinapp.io/topics/news/v1/?page=1&auth_api_key=’, url: function() { return this.url_base + this.public_api_key }, parse: function(response) { return response.response.news; } });

How can we test this collection and this model ? The javascript console integrated with Chrome, or Firebug inside the web browser Firefox.

In Chrome, load the HTML page just created. And, you could follow next operations:

  • Select the Wrench menu Tools -> Developer tools.
  • Right-click on any page element and select Inspect element.
  • Click on Console

Now, we are ready to create an instance of our new collection in the javascript console:

Console in Chrome

And yes, the post is finished !! ;) Well, I’ll provide some explanation. Collections make a link between the model News and information provided by the RESTful service newsinapp.io. The fetch() method allows to update the list of news. Then, you can see that we have retrieved 20 news (“length: 20”), and all news have some attributes as source, title or subtitle.

However, by default, Backbone.js does not know the API newsinapp.io. To solve this problem, we need to manage two steps. First, the url() method provides the API location. Second, we need to implement parse() method. It is a mapping between JSON response and News model. In this case, from JSON, the news list can be found in path ‘response/news’ (xpath syntax):

parse: function(response) {
    return response.response.news;
}

Magic ? But, wait a moment. I cannot call a JSON RESTful api on my web site, if this api is provided from an other web domain: “the URL replying to the request must reside within the same DNS domain as the server that hosts the page containing the request”. Usually, JSONP should be the solution for this problem. But, not really a beautiful solution !

In this case, newsinapp.io is CORS compatible . Then, nothing to do. It works.

That’s all for today ! Feel free to make your comments (at least constructively;)). This is my first post…

Next part: Using backbone views

Next entry

blog comments powered by Disqus