Reputation: 564
I'm brand new to Backbone and am having trouble finding information on how to access specific values from a collection. In this demo, I'm trying to grab the "image_url" value from my collection and put it in the template. I can't figure out how to do that.
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>
Model:
Shot = Backbone.Model.extend({
initialize: function(opts) {}
});
Collection:
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";
}
});
View:
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();
Upvotes: 1
Views: 39
Reputation: 1977
The problem you're encountering is your collection doesn't have image_url
. The collection's shot models will each have image_url
.
You can use an underscore function to just get an array of each shot's image_url:
this.collection.pluck("image_url")
However, this won't work within your template. Your template will receive an array, but the template itself is trying to access image_url on an object
Upvotes: 2