0

如何从backbone.collectionbyusername而不是获取特定行id

我认为最常见的情况,

site.come/#edit_contact/5

但我需要通过用户名/电子邮件或代码从集合中获取项目,

site.come/#edit_contact/user1
site.come/#edit_contact/lau@xxx.com
site.come/#edit_contact/T1X0A7

id的骨干,

model = AB.contactscollection.get(id);

理想情况下,

model = AB.contactscollection.get(username);

可能吗?

笔记:

我正在使用本教程中的代码进行测试,

http://amitgharat.wordpress.com/2012/06/23/writing-your-first-application-using-backbone-js/

编辑:

    var contact = {},

    //model = AB.contactscollection.get(id);
    model = AB.contactscollection.where({email: "lau@xxxx.com"})
    if (id !== undefined && model !== undefined) {

        contact = model.toJSON();
    }
    this.$el.html(this.template({contact: contact}));

错误信息,

类型错误:model.toJSON 不是函数

联系人 = model.toJSON();

4

1 回答 1

1

如果要根据模型属性从集合中获取模型,可以使用 where:

collection.where({username: "user1"});

请参阅此处的文档:Collection where

编辑:

如果您始终根据用户名或电子邮件属性选择模型,则可以将其设为 idAttribute,然后如果用户名是唯一的,则将其用作您的 id:

在模型中:

idAttribute: "username"

然后基于此从集合中获取模型:

collection.get("user1");

编辑2:

如果您只想从您的集合中返回一个模型(找到的第一个模型),请在文档中查找findWhere,您应该确保要搜索的属性是唯一的:

collection.findWhere({username: "user1"});
于 2013-11-29T09:56:06.313 回答