我正试着用backbone来抓取instagram订阅。这不需要对用户进行身份验证,它是通过以下方式获取一个公共提要:
https://api.instagram.com/v1/users/<user_id>/media/recent/?client_id=<client_id>
我已经将JSON响应输出到控制台,但我无法使其显示在我的页面上。
在下面的代码中,我使用fetchData获取提要,我希望最终能让render输出在#social
上样式化的所有内容。但是,尽管将feed属性设置为JSON响应,render
仍然返回一个空对象。但是,fetchData
中的console.log
会显示正确的信息。
var social = {}
social.Instagram = Backbone.Model.extend();
social.InstagramFeed = Backbone.Collection.extend({
model: social.Instagram,
url: 'https://api.instagram.com/v1/users/<user_id>/media/recent/?client_id=<client_id>',
parse: function(response) {
return response.results;
},
sync: function(method, model, options) {
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: this.url,
processData: false
}, options);
return $.ajax(params);
}
});
social.InstagramView = Backbone.View.extend({
el: '#social',
feed: {},
initialize: function() {
this.collection = new social.InstagramFeed();
this.fetchData();
this.render();
},
render: function() {
console.log(this.feed);
},
fetchData: function() {
this.collection.fetch({
success: function(collection, response) {
// console.log(response);
feed = response;
// console.log(this.feed);
},
error: function() {
console.log("failed to find instagram feed...");
}
});
}
});
social.instagramview = new social.InstagramView;
我曾尝试仅使用fetchData
函数输出信息,但是this.el.append(response)
会显示一条通知,指出el
未定义。
发布于 2014-09-06 21:07:14
您的render
方法在获取完成之前被调用。您应该绑定到集合的sync
事件,并在事件处理程序中调用render。
social.InstagramView = Backbone.View.extend({
el: '#social',
feed: {},
initialize: function() {
this.collection = new social.InstagramFeed();
this.fetchData();
this.collection.on('sync', function(){
this.render();
}, this);
// this.render();
},
...
})
引用Backbone.js文档:触发同步事件:
当模型或集合与服务器成功同步时为
。
https://stackoverflow.com/questions/25703887
复制