Backbone-relational cannot instantiate two RelationalModel objects

China☆狼群 提交于 2019-12-08 19:19:04

问题


I am trying to implement BackboneRelational and keep getting

"Cannot instantiate more than one Backbone.RelationalModel with the same id per type!"

class App.Models.User extends Backbone.RelationalModel
  urlRoot : '/api/users'
  idAttribute: 'id'

  relations: [
    type: Backbone.HasMany
    key: 'plots'
    relatedModel: 'App.Models.Plot'
    collectionType: 'App.Collections.Plots'
    includeInJSON: false
    reverseRelation:
      key: 'user_id',
      includeInJSON: 'id'
  ]


class App.Models.Plot extends Backbone.RelationalModel
  urlRoot : '/api/plots'
  idAttribute: 'id'

If I switch one of the models to extends Backbone.Model I can instantiate both, but I get all the warnings that the relational functionality is broken..

I am trying to achieve the following:

 plot = new App.Models.Plot({id : 700})
 plot.fetch()
 plot.get('user')

What am I missing?


回答1:


The general idea behind the "one model per id" situation is that Backbone Relational uses a data store (Backbone.Relational.store) to eliminate repeated requests for models that have already been loaded.

Fortunately, it also provides a few helpers to help access models through the store. Instead of supplying an ID and fetching the plot, you might instead use the findOrCreate method you'll find attached to App.Models.Plot:

plot = App.Models.Plot.findOrCreate(700)
user = plot.get('user')


来源:https://stackoverflow.com/questions/12224122/backbone-relational-cannot-instantiate-two-relationalmodel-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!