Fun with Twitter json with backbone.js

credits: http://stackoverflow.com/questions/13068597/how-to-get-json-with-backbone-js/13069500#13069500

by deanpeters

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>hello-backbonejs</title>
</head>
<body>
    <div id="test"></div>
</body>
</html>

JavaScript

var Item = Backbone.Model.extend();

var List = Backbone.Collection.extend({
    model: Item,

    url: "http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&result_type=mixed",

    parse: function(response) {
        return response.results;
    },

    sync: function(method, model, options) {
        var that = this;
        var params = _.extend({
            type: 'GET',
            dataType: 'jsonp',
            url: that.url,
            processData: false
        }, options);

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

var ListView = Backbone.View.extend({
    el: $('#test'),
    events: {
        'click button#add': 'getPost'
    },
    initialize: function() {
        _.bindAll(this, 'render', 'getPost');
        this.collection = new List();
        this.render();
    },
    render: function() {
        var self = this;
        $(this.el).append("<button id='add'>get</button>");
    },
    getPost: function() {
        var that = this;
        this.collection.fetch({
            success: function() {
                console.log(that.collection.toJSON());
            },
            error: function() {
                console.log('Failed to fetch!');
            }

        });
    }

});

// **listView instance**: Instantiate main app view.
var listView = new ListView();