主干模板数据显示在console.log中,但不显示在页面上

Backbone template data shows up in console.log but not on page

本文关键字:显示 console 数据 log      更新时间:2023-09-26

我是Backbone的新手,我已经从Instagram上获取了一组数据,并通过将其附加到一个容器将其输出到页面上(在下面的代码中注释)。但是,我希望使用模板系统来处理输出。这就是它分崩离析的地方,我现在开始认为我甚至没有正确设置它。我觉得我的视图中的fetchData方法应该是属于集合的方法,而render方法中的循环应该是属于该集合的方法。

撇开正确的实践不谈,我遇到的主要问题是,当我试图将数据传递到模板时,结果是空白的。但是,当我从模板中console.log时,我可以看到所有必要的信息。

这是我的JS文件

var social = {}
/*
*
* MODELS
*
*/
social.Instagram = Backbone.Model.extend();
/*
 *
 * COLLECTIONS
 *
 */
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;
  },
  sync: function(method, model, options) {
    var params = _.extend({
        type: 'GET',
        dataType: 'jsonp',
        url: this.url,
        processData: false
    }, options);
    return $.ajax(params);
  }
});
/*
 *
 * VIEWS
 *
 */
social.InstagramView = Backbone.View.extend({
  el: '#social',
  feed: {},
  initialize: function() {
    this.collection = new social.InstagramFeed();
    this.collection.on('sync', this.render, this);
    this.fetchData();
  },
  render: function() {
    var images = {};
    // var images = '';
    for(var i = 0; i < this.feed.length; i++) {
        var photo = this.feed[i].images.standard_resolution.url;
        var caption = this.feed[i].caption == null ? 'no caption' : this.feed[i].caption.text;
        var likes = this.feed[i].likes.count;
        var id = this.feed[i].id;
        // images += '<img src="'+photo+'" data-caption="'+caption+'" data-likes="'+likes+'" data-id="'+id+'" alt="">';
        images[i] = {'photo': photo, 'caption': caption, 'likes': likes, 'id': id};
    }
    // this.model = images;
    // $('#social').append(images);
    var template = _.template($('#instagram-template').html());
    this.$el.html(template({ collection: images }));
  },
  fetchData: function() {
    var self = this;
    this.collection.fetch({
        success: function(collection, response) {
            self.feed = response.data;
        },
        error: function() {
            console.log("failed to find instagram feed...");
        }
    });
  }
});
social.instagramview = new social.InstagramView;

模板文件

<script type="text/template" id="instagram-template">
  <% _.each(collection, function(item) { %>
    <img src="<%= item.photo %>"> // this doesn't work
    <% console.log(item.photo) %> // this works
  <% }); %>
</script>

我走对了吗?我是否应该考虑重组我的控制器和视图之间的逻辑?

下面是用户2989731:的解决方案

在加载模板脚本之前加载脚本时出现问题。当脚本加载到页面底部时,它开始工作。