未捕获的错误:无法为每个类型实例化多个具有相同id的Backbone.RelationalModel

Uncaught Error: Cannot instantiate more than one Backbone.RelationalModel with the same id per type

本文关键字:RelationalModel Backbone id 实例化 类型 错误      更新时间:2023-09-26

我在Backbone Marionette应用程序中使用Backbone Relational。如果我遵循此工作流:直接导航到显示页面>单击"主页"(或索引页面)链接>单击浏览器的后退按钮返回显示页面我收到一个导致页面无法加载的错误:

Uncaught Error: Cannot instantiate more than one Backbone.RelationalModel with the same id per type! 

问题似乎是模型已经在内存中了,所以Backbone Relational不想重新获取它。它有一个内置的助手来帮助实现这一点——findOrCreate。我遵循了backenerails.com教程,该教程帮助您设置了一个漂亮的"when:pautched"函数,该函数基本上在从服务器获取模型后运行您想要运行的任何代码。

我一直试图将其调整为使用findOrCreate函数,但到目前为止都没有成功。有什么想法我应该如何更新它以使用findOrCreate调用而不是fetch调用吗?

@TheoremReach.module "Utilities", (Utilities, App, Backbone, Marionette, $, _) ->
  App.commands.setHandler "when:fetched", (entities, callback) ->
    xhrs = _.chain([entities]).flatten().pluck("_fetch").value()
    $.when(xhrs...).done ->
      callback()

或者,有没有一种方法可以访问已经存在并引发此错误的"内存中的模型"?我一直在搜索,但没能弄清楚它存储在哪里/如何访问它。

提前感谢!

只需使用findOrCreate实例化模型,然后获取它。

var model = MyModel.findOrCreate({id : modelId});
model.fetch();