6

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?

Linus Oleander
  • 17,746
  • 15
  • 69
  • 102

2 Answers2

15

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:

Iterate over elements and map the result:

var result = friends.where({job: "Musketeer"});
_.map( result, function( model ){ return model.toJSON(); } );

jsFiddle code

Implement a Collection searcher method that returns a proper Backbone.Collection:

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

fguillen
  • 36,125
  • 23
  • 149
  • 210
5

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.

Community
  • 1
  • 1
nikoshr
  • 32,926
  • 33
  • 91
  • 105