簡體   English   中英

與第三方api一起使用主干

[英]using backbone with third party api

我正在嘗試使用中堅力量來抓取instagram feed。 這不需要驗證用戶身份,它可以通過以下方式獲取可用的公共供稿:

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

我已經將JSON響應輸出到控制台了,但是我無法使其顯示在頁面上。

在下面的代碼中,我使用fetchData來獲取提要,並且最終希望使它達到渲染輸出在#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未定義。

在獲取完成之前,將調用您的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文檔:觸發了同步事件:

模型或集合已成功與服務器同步。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM