大家好,我是 Backbone.js 的新手。我正在尝试让我的收藏与基于 RESTful python 谷歌应用引擎的后端一起工作。这是服务器上使用的代码:
def getJson():
tweets_out = []
tweets = getModTweets()
for tweet in tweets:
temp = {}
temp["screen_name"] = tweet.screen_name
temp["text"] = tweet.text
temp["profile_image_url"] = tweet.profile_image_url
temp["id"] = tweet.id
temp["created_at_time"] = tweet.created_at_time
temp["created_at_epoch"] = tweet.created_at_epoch
temp["time_lapsed"] = tweet.time_lapsed
tweets_out.append(temp)
a = json.dumps(tweets_out)
return a
生成的 JSON 如下:
[{"screen_name": "spolsky", "text": "@greeleygeek I'm going to start doing that", "profile_image_url": "http://a0.twimg.com/profile_images/1770014670/image1327118364_normal.png", "time_lapsed": "3 days ago", "created_at_epoch": 1346464678, "created_at_time": "2012-9-1 01:57:58", "id": 15948437}, {"screen_name": "spolsky", "text": "@phlix google analytics.", "profile_image_url": "http://a0.twimg.com/profile_images/1770014670/image1327118364_normal.png", "time_lapsed": "4 days ago", "created_at_epoch": 1346439185, "created_at_time": "2012-8-31 18:53:05", "id": 15948437}, {"screen_name": "spolsky", "text": "@AdityaAthalye we make it up in volume!", "profile_image_url": "http://a0.twimg.com/profile_images/1770014670/image1327118364_normal.png", "time_lapsed": "4 days ago", "created_at_epoch": 1346425278, "created_at_time": "2012-8-31 15:01:18", "id": 15948437}]
我尝试使用以下两种方法尝试通过以下两种方式填充我的集合,但均未成功:
var Tweet = Backbone.Model.extend({
urlRoot : '/tweets.json'
});
var Tweets = Backbone.Collection.extend({
model: Tweet,
url: '/bulktweets.json'
});
var tweets2 = new Tweets();
//method 1
tweets2.reset(JSON STRING LISTED ABOVE);
//Yes tweets2.reset([{"screen_name": "spolsky", "text": "@greeleygeek I'm going to start doing that", "profile_image_url": "http://a0.twimg.com/profile_images/1770014670/image1327118364_normal.png", "time_lapsed": "3 days ago", "created_at_epoch": 1346464678, "created_at_time": "2012-9-1 01:57:58", "id": 15948437}, {"screen_name": "spolsky", "text": "@phlix google analytics.", "profile_image_url": "http://a0.twimg.com/profile_images/1770014670/image1327118364_normal.png", "time_lapsed": "4 days ago", "created_at_epoch": 1346439185, "created_at_time": "2012-8-31 18:53:05", "id": 15948437}, {"screen_name": "spolsky", "text": "@AdityaAthalye we make it up in volume!", "profile_image_url": "http://a0.twimg.com/profile_images/1770014670/image1327118364_normal.png", "time_lapsed": "4 days ago", "created_at_epoch": 1346425278, "created_at_time": "2012-8-31 15:01:18", "id": 15948437}
]);
//method 2
tweets2.fetch();
溢出者可能会指出我正确的方向吗?提前致谢。
更新: 我能够与服务器通信,但整个集合不只解析第一个元素。
为什么我会得到集合,即 tweets2.length 返回长度为 1 而不是预期的 5?有人可以阐明一些吗?