Reputation: 18137
I'm not sure why, but I can't get this to work.
var friends = new Backbone.Collection([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan", job: "Guard"},
]);
friends.where({job: "Musketeer"}).toJSON()
I'm getting Uncaught TypeError: Object [object Object] has no method 'toJSON'
.
What I'm I doing wrong and how do I convert my filtered collection into JSON?
Upvotes: 6
Views: 8608
Reputation: 38832
What the Underscore.where
method returns is an Array
not a Backbone.Collection
so it has not the toJSON
method defined.
So you can make two things:
var result = friends.where({job: "Musketeer"});
_.map( result, function( model ){ return model.toJSON(); } );
var Friends = Backbone.Collection.extend({
search: function( opts ){
var result = this.where( opts );
var resultCollection = new Friends( result );
return resultCollection;
}
});
var myFriends = new Friends([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan", job: "Guard"},
]);
myFriends.search({ job: "Musketeer" }).toJSON();
Upvotes: 15
Reputation: 33364
toJSON
is a confusing method name : http://documentcloud.github.com/backbone/#Collection-toJSON
toJSON
collection.toJSON()
Return an array containing the attributes hash of each model in the collection. This can be used to serialize and >persist the collection as a whole. The name of this method is a bit confusing, because it conforms to JavaScript's >JSON API.
if you want to convert your collection to a JSON string, use JSON.stringify
var friends = new Backbone.Collection([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan", job: "Guard"},
]);
JSON.stringify( friends.where({job: "Musketeer"}) );
Note that where
returns an array, not a Backbone collection, you would have to build a new collection to use the toJSON
method.
Upvotes: 5