主干模板数据显示在console.log中,但不显示在页面上
Backbone template data shows up in console.log but not on page
我是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:的解决方案
在加载模板脚本之前加载脚本时出现问题。当脚本加载到页面底部时,它开始工作。
相关文章:
- Array.length似乎不起作用;console.log则显示其他情况
- AngularJS:console.log不显示任何内容
- console.log在FF插件生成器中没有显示任何内容
- 使用console.log在对象中显示值
- 在JavaScript的HTML元素中显示console.log()
- Node Defender控制台没有't显示console.error()消息
- console.log() 在变量值实际更改之前显示变量的更改值
- 如何在 eclipse console 中显示 javascript 控制台.log
- Console.log显示隐藏的对象信息
- console.log和进度事件-仅在100%时显示
- console.log未显示在屏幕上
- 我可以在Iframe上显示console.log消息吗
- 为什么console.log()显示一个数组,而typeof返回'对象'
- 在console.log中调用jQuery实例时,jQuery实例如何显示为数组
- console.log未显示预期的对象属性
- 主干模板数据显示在console.log中,但不显示在页面上
- 在console.log中显示ngResource对象
- Node js console.log没有显示任何内容
- 在JavaScript中,console.log给出了for循环的每个值.但是var.text只显示最后一个值.这是为什
- 打印或显示console.log中变量的当前值