在 the O'Reilly 'Developing backbone.js applications'对于覆盖 Backbone.sync 的示例,有以下逻辑来运行示例 findAll()
与 find()
方法:
case 'read':
if (model.attributes[model.idAttribute]) {
return MyAPI.find(model, success, error);
} else {
return MyAPI.findAll(model, success, error);
}
}
在 Collection
上运行 fetch()
会导致以下错误:model.idAttribute 未定义
这是因为调用 myCollection.fetch()
时参数 model
包含一个集合。所以它不包含idAttribute
。
在我看来,简单地测试 model.idAttribute
是否存在就足以区分 Model
和 Collection
,命令在 find()
和 findAll()
之间切换。
我还缺少其他东西吗?这是权威资源。
最佳答案
代码修复可能应该是这样的
case 'read':
if (model.idAttribute) {
if (model.attributes[model.idAttribute]) {
return MyAPI.find(model, success, error);
}
} else {
return MyAPI.findAll(model, success, error);
}
您需要对两者进行测试,因为模型可能会使用 idAttribute
值定义哪个属性是它的 id,但实际的 id 值可能不存在。换句话说,如果您收到的模型实例是
{
idAttribute: "myId",
name: "test"
}
您无法调用 find
方法,因为您必须在查询中使用 id 值(即 myModel.get("myId")
不会返回任何内容)。
关于javascript - 在主干同步覆盖中“读取”集合逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21525470/