Backbone - Get JSON Data from API

2019-04-10 17:40发布

I'm playing around with Backbone these last days..

I want to receive some data from the twitter search API. But I don't really understand how it works. This is my code:

(function($){

Tweet = Backbone.Model.extend();

Tweets = Backbone.Collection.extend(
    {
        model: Tweet,

        url: 'http://search.twitter.com/search.json?q=Hamburg&rpp=5&lang=all&callback=?',
        parse: function(response)
        {
            return response.results;
        }
    });

DefaultTweetView = Backbone.View.extend(
    {
        initialize: function(){
          _.bindAll(this, 'render');
     }

        template: _.template('<p>@<%= from_user %> <em></em></p><p><%= text %></p><p><%= location %></p>'),
        render: function()
        {

            $(this.el).html(this.template(this.model.toJSON()));
            return this;
        }
    });
app = new Tweet();
})(jQuery);

I don't think this could be right. But I don't know how to handle it :( Could someone help me or post a link where I could follow some instructions about json data and backbone please?

1条回答
时光不老,我们不散
2楼-- · 2019-04-10 18:08

Expications

Your actual code doesn't work because you have a syntax error, and you just initialized the model.

You can't access to Twitter API without overwrite the Backbone.sync method (problem of the same origin policy : http://en.wikipedia.org/wiki/Same_origin_policy, the solution has already posted here : Backbone Collection jsonp ajax results not generating model correctly)

In my view, the best thing to learn Backbone JS is to understand how code works, and to help you, the Backbone JS documentation is here : http://documentcloud.github.com/backbone/

Example

I created a working jsFiddle with your code here : http://jsfiddle.net/Atinux/v4K6A/

So with it you can begin to better understand Backbone JS.

查看更多
登录 后发表回答