使用带有第三方api的主干网

using backbone with third party api

本文关键字:api 主干网 第三方      更新时间:2023-09-26

我正在尝试使用主干来获取instagram提要。这不需要对用户进行身份验证,而是通过以下途径获取可用的公共提要:

https://api.instagram.com/v1/users/<user_id>/media/recent/?client_id=<client_id>

我已经将JSON响应输出到控制台,但我无法在页面上显示它。

在下面的代码中,我使用fetchData来获取提要,我希望最终使其达到render输出#social上风格化的所有内容的程度。然而,尽管将提要属性设置为JSON响应,render仍然返回一个空对象。CCD_ 5中的CCD_。

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事件,并在事件处理程序中调用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文档:同步事件被触发:

模型或集合已成功与服务器同步。