[stackOverflow] Backbone - Get JSON Data from API

http://stackoverflow.com/questions/8660648/backbone-get-json-data-from-api

by FiNGAHOLiC

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<!-- Template of the Tweets View -->
<script type="text/template" id="tweetsTemplate">
    <% _.each(tweets, function (tweet) { %>
    <div class="tweet">
        <p>@<%= tweet.from_user %></p>
        <p class="text"><%= tweet.text %></p><p><%= tweet.location %></p>
    </div>
    <% }); %>
</script>

CSS

.tweet {
    background: rgb(245,245,245);
    border: 1px rgb(120,120,120) solid;
    border-radius: 5px;
    margin: 5px;
    padding: 5px;
}

.text {
    color: rgb(80,80,80);
}

JavaScript

// Define the model
Tweet = Backbone.Model.extend();

// Define the collection
Tweets = Backbone.Collection.extend(
    {
        model: Tweet,
        // Url to request when fetch() is called
        url: 'http://search.twitter.com/search.json?q=Hamburg&rpp=5&lang=all',
        parse: function(response) {
            return response.results;
        },
        // Overwrite the sync method to pass over the Same Origin Policy
        sync: function(method, model, options) {
            var that = this;
                var params = _.extend({
                    type: 'GET',
                    dataType: 'jsonp',
                    url: that.url,
                    processData: false
                }, options);

            return $.ajax(params);
        }
    });

// Define the View
TweetsView = Backbone.View.extend({
    initialize: function() {
      _.bindAll(this, 'render');
      // create a collection
      this.collection = new Tweets;
      // Fetch the collection and call render() method
      var that = this;
      this.collection.fetch({
        success: function () {
            that.render();
        }
      });
    },
    // Use an extern template
    template: _.template($('#tweetsTemplate').html()),

    render: function() {
        // Fill the html with the template and the collection
        $(this.el).html(this.template({ tweets: this.collection.toJSON() }));
    }
});

var app = new TweetsView({
    // define the el where the view will render
    el: $('body')
});