繁体   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