【发布时间】:2014-09-08 05:23:48
【问题描述】:
我是 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>
我在正确的轨道上吗?我应该考虑重构控制器和视图之间的逻辑吗?
【问题讨论】: