Javascript ';阅读';主干同步覆盖中的收集逻辑
在覆盖Backbone.sync的示例中,有以下逻辑运行示例Javascript ';阅读';主干同步覆盖中的收集逻辑,javascript,backbone.js,backbone.js-collections,Javascript,Backbone.js,Backbone.js Collections,在覆盖Backbone.sync的示例中,有以下逻辑运行示例findAll()vsfind()方法: case 'read': if (model.attributes[model.idAttribute]) { return MyAPI.find(model, success, error); } else { return MyAPI.findAll(model, success, error); } } 对集合运行fetch()会导致以下错误:model.id
findAll()
vsfind()
方法:
case 'read':
if (model.attributes[model.idAttribute]) {
return MyAPI.find(model, success, error);
} else {
return MyAPI.findAll(model, success, error);
}
}
对集合运行fetch()
会导致以下错误:model.idAttribute未定义
这是因为调用myCollection.fetch()
时,参数model
包含一个集合。因此它不包含idAttribute
在我看来,为了在find()
和findAll()
之间切换,简单地测试model.idAttribute
的存在就足以区分model
和Collection
我是不是还遗漏了什么?这是一个权威资源。代码修复程序可能类似于
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”)
不会返回任何内容)。您可以尝试instanceof
:
case 'read':
if (model instanceof Backbone.Model && model.idAttribute) {
return MyAPI.find(model, success, error);
} else if (model instanceof Backbone.Collection) {
return MyAPI.findAll(model, success, error);
} else {
// the model have no idAttribute
}
}
虽然,您可以在find()中处理这个问题,但您的示例没有使用instanceof?@robC我不知道发生了什么,但我的答案的最后编辑丢失了:)哈哈,谢谢,我觉得更清楚了。但是如果idAttribute测试是duck类型,那么在您的示例中它是多余的。我添加它只是为了防止您想要处理这个案例。