javascript – Backbone.Collection通过id获取模型

栏目: JavaScript · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/14299992/backbone-collection-get-model-by-id

我有一个从服务器获取模型的集合.

这样做,现在我想用MyCollection.at(0)的id来获取一个模型,我得到:

child
_changes: Array[0]
_changing: false
_currentAttributes: Object
_events: Object
_hasComputed: true
_pending: false
_previousAttributes: Object
attributes: Object
_id: "50ef7a63b2a53d17fe000001"
author_name: "author name"
bookmark: ""
info: "bookmark description"
__proto__: Object
changed: Object
cid: "c26"
collection: child
view: child
__proto__: Surrogate

如果我试图通过它的id获得模型:

MyCollection.get("50ef7a63b2a53d17fe000001")
=> undefined

MyColleciton.get({_id:"50ef7a63b2a53d17fe000001"})
=> undefined

MyCollection.get({'_id':"50ef7a63b2a53d17fe000001"})
=> undefined

我不明白 – 文档清楚地表明.get()方法将返回模型,如果该集合中存在给定ID的模型.

你在模型上设置了 Model.idAttribute

吗?

var Model = Backbone.Model.extend({
    idAttribute:"_id"
});

默认情况下,Backbone希望将id属性称为id.当设置了idAttribute时,Backbone会标准化id的处理,以便始终可以使用model.id,即使id属性被称为别的东西.原始id属性在Model的属性哈希中可用,并且通过getmetd可以使用.所以:

model.id === model.get('_id') // -> true

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/14299992/backbone-collection-get-model-by-id


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Cracking the Coding Interview

Cracking the Coding Interview

Gayle Laakmann McDowell / CareerCup / 2015-7-1 / USD 39.95

Cracking the Coding Interview, 6th Edition is here to help you through this process, teaching you what you need to know and enabling you to perform at your very best. I've coached and interviewed hund......一起来看看 《Cracking the Coding Interview》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具