4

プロジェクトでバックボーン リレーショナルと CoffeeScript を使用しようとしています。以下は、モデル化しようとしているタイプの CoffeeScript の例です。

  class NestedModel extends Backbone.RelationalModel
    defaults:
     Description: 'A nested model'

  NestedModel.setup()

  class MainModel extends Backbone.RelationalModel
    defaults:
     Description: 'A MainModel description'
     StartDate: null

    relations: [
      type: Backbone.HasOne
      key:  'nestedmodel'
      relatedModel: 'NestedModel'
      includeInJSON: '_id'
      reverseRelation:
        type: Backbone.HasOne
        includeInJSON: '_id'
        key: 'mainmodel'   
    ]

  MainModel.setup()     

  nm = new NestedModel()
  mm = new MainModel(nestedmodel: nm)
  console.log mm.get("nestedmodel").get("mainmodel").get("Description")
  return 

この CoffeeScript は、次の JavaScript を生成します。

  var MainModel, NestedModel, mm, nm;
  var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
    for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
    function ctor() { this.constructor = child; }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor;
    child.__super__ = parent.prototype;
    return child;
  };
  NestedModel = (function() {
    __extends(NestedModel, Backbone.RelationalModel);
    function NestedModel() {
      NestedModel.__super__.constructor.apply(this, arguments);
    }
    NestedModel.prototype.defaults = {
      Description: 'A nested model'
    };
    return NestedModel;
  })();
  NestedModel.setup();
  MainModel = (function() {
    __extends(MainModel, Backbone.RelationalModel);
    function MainModel() {
      MainModel.__super__.constructor.apply(this, arguments);
    }
    MainModel.prototype.defaults = {
      Description: 'A MainModel description',
      StartDate: null
    };
    MainModel.prototype.relations = [
      {
        type: Backbone.HasOne,
        key: 'nestedmodel',
        relatedModel: 'NestedModel',
        includeInJSON: '_id',
        reverseRelation: {
          type: Backbone.HasOne,
          includeInJSON: '_id',
          key: 'mainmodel'
        }
      }
    ];
    return MainModel;
  })();
  MainModel.setup();
  nm = new NestedModel();
  mm = new MainModel({
    nestedmodel: nm
  });
  console.log(mm.get("nestedmodel").get("mainmodel").get("Description"));
  return;

次の警告とエラーが生成されます

Warning:
Relation= child
; no model, key or relatedModel (function MainModel() {
              MainModel.__super__.constructor.apply(this, arguments);
            }, "nestedmodel", undefined)


Error:
Uncaught TypeError: Cannot call method 'get' of undefined

生成された JavaScript の 1 行目から「NestedModel」変数を単純に削除する

var MainModel, NestedModel, mm, nm;

正しい動作を引き起こします。明らかに、生成された JavaScript から変数定義を削除し続けることはできません。私は何を間違っていますか?

わかりました、それはスコープの問題のようです。次のjsFiddle の例を参照してください。しかし、ローカル関数スコープ内のクラスを参照できないのはなぜですか?

4

1 に答える 1