Linus Oleander
Linus Oleander

Reputation: 18137

toJSON on Backbone.Collection#where?

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

Answers (2)

fguillen
fguillen

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:

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

Upvotes: 15

nikoshr
nikoshr

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

Related Questions