Reputation: 1065
I'm trying to learn a little bit of backbone.js and I'm getting stuck on something I think should be fairly simple to figure out. How do I get a list of all model names in a collection?
I'm even copy+pasting from the backbone tutorial:
var Song = Backbone.Model.extend({
defaults: {
name: "Not specified",
artist: "Not specified"
},
initialize: function(){
console.log("Music is the answer");
}
});
var Album = Backbone.Collection.extend({
model: Song
});
var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });
var myAlbum = new Album([ song1, song2, song3]);
console.log( myAlbum.models ); // [song1, song2, song3]
The problem is - this doesn't give me model names in the console:
console.log( myAlbum.models ); // [song1, song2, song3]
instead I get [child, child, child, child] - how do I get the actual names?
Upvotes: 0
Views: 1374
Reputation: 161467
You need to pluck
the name
attribute.
myAlbum.pluck('name');
There is no way to get an array like this:
['song1', 'song2', 'song3']
because names of variables are not available in program logic.
When the tutorial writes this:
console.log( myAlbum.models ); // [song1, song2, song3]
It means that the array models
is the same as if you were to write [song1, song2, song3]
, not as if you were to write ['song1', 'song2', 'song3']
. The quotes are the differentiating factor.
Upvotes: 2