我不知道为什么,但我无法让它发挥作用。
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?
答案 0 :(得分:15)
Underscore.where
方法返回的内容是Array
而不是Backbone.Collection
,因此未定义toJSON
方法。
所以你可以做两件事:
var result = friends.where({job: "Musketeer"});
_.map( result, function( model ){ return model.toJSON(); } );
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();
答案 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
方法。