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?
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(); } );
jsFiddle code
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();
jsFiddle code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With