无法提取使用Backbone.js的集合来自Twitter的RESTful API数据 [英] Unable to fetch data from Twitter RESTful API using Backbone.js Collection

查看:137
本文介绍了无法提取使用Backbone.js的集合来自Twitter的RESTful API数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习从使用Backbone.js的收集方法数据库中提取数据:fetch()方法。

I'm trying to learn to fetch data from a database using the Backbone.js Collection method: fetch().

本的jsfiddle例子是这里

The jsfiddle example is here.

返回的对象的长度为零,这意味着我没有得到任何结果回来。我可以使用jQuery阿贾克斯很容易获得JSON和Backbone.sync显然使用阿贾克斯方法了。我想知道什么是错的?

The object's length returned is zero which means I'm not getting any result back. I can very easily obtain the json using jquery ajax and Backbone.sync is apparently using the .ajax method too. May I know what's wrong?

推荐答案

您要在两个问题上运行。

You're running across two issues.

首先是Twitter的结果(你想变成骨干机型是什么)位于下结果属性。要使用此数据,您需要覆盖集合中的解析方法。这是在骨架文档使用的特定示例:

The first is that twitter's results (what you want to turn into backbone models) resides under a "results" property. To use this data, you need to override the parse method in the collection. This is the specific example used in the backbone docs:

<一个href=\"http://documentcloud.github.com/backbone/#Collection-parse\">http://documentcloud.github.com/backbone/#Collection-parse

第二个问题是,fetch()方法是异步的,所以,当你得到在集合的长度,回应之前的发生从Twitter返回的,所以它仍是0长度。

The second issue is that the fetch() method is asynchronous, so that when you're getting the 'length' on the collection, its happening before the response comes back from twitter, so its still 0 length.

您需要设置一个事件处理程序侦听的取的结果,然后输出长度:

You need to set up an event handler to listen for the results of the "fetch" and THEN output the length:

var Tweet = Backbone.Model.extend();

var Tweets = Backbone.Collection.extend({
    model: Tweet,
    url: 'http://search.twitter.com/search.json?q=obama&callback=?',
    parse: function(response) {
        return response.results;
    }
});

var tweets = new Tweets();

tweets.bind('reset', function(collection) {
   alert(collection.length);
});

tweets.fetch();

这篇关于无法提取使用Backbone.js的集合来自Twitter的RESTful API数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆