我是 Backbone 的新手,无法找到有关如何从集合中访问特定值的信息。在此演示中,我试图从我的集合中获取“image_url”值并将其放入模板中。我不知道该怎么做。
HTML
<script type="text/template" id="dribble_details">
<div class="row">
<div class="col-xs-6 col-md-3">
<a href="#" class="thumbnail">
<img src="<%= image_url %>">
</a>
</div>
</script>
型号:
Shot = Backbone.Model.extend({
initialize: function(opts) {}
});
收藏:
ShotsList = Backbone.Collection.extend({
model: Shot,
sync: function(method, model, options) {
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: model.url(),
processData: false
}, options);
return $.ajax(params);
},
parse: function(response) {
return response.shots;
},
url: function() {
return "http://api.dribbble.com//shots?per_page=12/popular";
}
});
查看:
DribbleView = Backbone.View.extend({
el : $('#dribble_container'),
template : _.template($('#dribble_details').html()),
initialize : function() {
var self = this;
self.collection = new ShotsList();
self.collection.fetch({
success: function(){
self.render();
}
});
},
render : function() {
this.$el.html(this.template( this.collection.get("image_url") ));
return this;
}
});
view1 = new DribbleView();
最佳答案
您遇到的问题是您的收藏没有image_url
。该系列的镜头模型将分别具有 image_url
。
您可以使用下划线函数来获取每个镜头的 image_url 数组:
this.collection.pluck("image_url")
但是,这在您的模板中不起作用。您的模板将接收一个数组,但模板本身正在尝试访问对象上的 image_url
关于javascript - 我应该如何使用主干 View 呈现集合的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20486253/