无法使用 Backbone.js Collection 从 Twitter RESTful API 获取数据 [英] Unable to fetch data from Twitter RESTful API using Backbone.js Collection

查看:18
本文介绍了无法使用 Backbone.js Collection 从 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 ajax 获取 json,而 Backbone.sync 显然也在使用 .ajax 方法.我可以知道出了什么问题吗?

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?

推荐答案

您遇到了两个问题.

首先是 twitter 的结果(你想变成主干模型的)位于results"属性下.要使用此数据,您需要覆盖集合中的 parse 方法.这是主干文档中使用的具体示例:

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:

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.

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

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 Collection 从 Twitter RESTful API 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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