Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toJSON on Backbone.Collection#where?

Tags:

backbone.js

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?

like image 599
Linus Oleander Avatar asked May 11 '12 09:05

Linus Oleander


1 Answers

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

like image 125
fguillen Avatar answered Oct 27 '22 10:10

fguillen