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 get Uncaught TypeError: Object [object Object] has no method 'toJSON' .

What am I doing wrong and how do I convert a filtered collection to JSON?

+6
source share
2 answers

What the Underscore.where method returns is Array not a Backbone.Collection , so it did not define a toJSON method.

So there are two things you can do:

Iterate over the elements and display the result:

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

jsFiddle code

Implement a collection search method that returns the correct 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

+15
source

toJSON is a confusing method name: http://documentcloud.github.com/backbone/#Collection-toJSON

toJSON collection.toJSON()

Returns an array containing a hash of attributes of each model in the collection. This can be used to serialize and> save the collection as a whole. The name of this method is a bit confusing because it matches the JavaScript> 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 will need to create a new collection to use the toJSON method.

+5
source

Source: https://habr.com/ru/post/915486/


All Articles