在Backbone.Collection上的toJSON#where?

时间:2012-05-11 09:17:38

标签: backbone.js

我不知道为什么,但我无法让它发挥作用。

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()

我正在Uncaught TypeError: Object [object Object] has no method 'toJSON'

我做错了什么以及如何将过滤后的集合转换为JSON?

2 个答案:

答案 0 :(得分:15)

Underscore.where方法返回的内容是Array而不是Backbone.Collection,因此未定义toJSON方法。

所以你可以做两件事:

迭代元素并映射结果:

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

jsFiddle code

实现Collection searcher方法,该方法返回正确的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

答案 1 :(得分:5)

toJSON是一个令人困惑的方法名称:http://documentcloud.github.com/backbone/#Collection-toJSON

  

toJSON collection.toJSON()

     

返回一个数组,其中包含集合中每个模型的属性hash。这可以用于序列化和>保持整个集合。此方法的名称有点令人困惑,因为它符合JavaScript的> JSON API。

如果要将集合转换为JSON字符串,请使用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"}) );

请注意,where返回一个数组,而不是Backbone集合,您必须构建一个新集合才能使用toJSON方法。