与第三方API使用骨干
问题描述:
我试图用骨干来抓住一个instagram feed。这并不需要验证用户身份,它是通过拉动可用公共提要:与第三方API使用骨干
https://api.instagram.com/v1/users/<user_id>/media/recent/?client_id=<client_id>
至于输出JSON响应到控制台我已经得到了,但我无法使它显示在我的页面上。
在下面的代码中,我使用fetchData来抓取提要,并且我想最终得到它的渲染输出在#social
上所有程式化的点。但是,尽管将Feed属性设置为JSON响应,但render
仍会返回空对象。 console.log
在fetchData
但是显示正确的信息。
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
未定义试图输出的信息。
答
您的render
方法在取回完成之前调用。您应该绑定到集合的sync
事件,并在事件处理函数中调用渲染。
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的文档:同步触发事件:
当一个模型或集合已与服务器成功同步。