0

我有简单的嵌套 JSON:

{
  "user": {
      "name": "John",

      "related": {
          "name": "Alice",

          "related": {
              "name": "Bob" 
          }
      }
   }
}

我有骨干关系模型“用户”:

(function(){
  var User = Backbone.RelationalModel.extend({
     defaults: {
       name: "",
       related: {}
     },
     // Linking this model to itself
     relations: [{
       type: Backbone.HasOne,
       key: "related",
       relatedModel: User // As I've expected it doesn't exist at this time
     }]
  })
})()

所以,问题是:如何将模型链接到自身?谢谢!

4

1 回答 1

1

Backbone.Relational “相关”模型需要在可访问范围内,在早期版本的 Backbone-Rel 中,它通常期望模型在全局范围内可访问。

但是,如果您使用 Require.js,或者将模型定义包装在一个闭包中,它们将不在该全局范围内。

这个拉取请求处理这种情况。使用 Backbone-Rel 的最新 HEAD,您可以为 Backbone-Rel 添加自定义范围以在以下位置查找相关模型:

(function(){
    var models = {};
    Backbone.Relational.store.addModelScope(models);

    models.User = Backbone.RelationalModel.extend({
     defaults: {
       name: ""
     },
     // Linking this model to itself
     relations: [{
       type: Backbone.HasOne,
       key: "related",
       relatedModel: 'User'
     }]
    });

    var u1 = new models.User({
      name: "John",
      related: {
          name: "Alice",
          related: {
              name: "Bob" 
          }
      }
    });

    console.log(u1.toJSON());

})();

现场 jsFiddle 示例:http: //jsfiddle.net/edwardmsmith/BRmQF/16/

于 2012-07-02T14:20:23.997 回答