上的toJSON#Backbone.Collection哪里? [英] toJSON on Backbone.Collection#where?

查看:131
本文介绍了上的toJSON#Backbone.Collection哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么,但我不能得到这个工作。

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

我收到未捕获类型错误:对象的翻译:没有法的toJSON

什么我是我做错了,我怎么转换我收集过滤成JSON?

What I'm I doing wrong and how do I convert my filtered collection into JSON?

推荐答案

什么 Underscore.where 方法返回的是一个阵列不是 Backbone.Collection 所以它有没有定义的的toJSON 方法。

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:

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

的jsfiddle code

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

这篇关于上的toJSON#Backbone.Collection哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆