2013-03-20 8 views
9

私は動物のコレクションを持っています。多型モデルのバックボーンコレクション

App.Collections.Animals extends Backbone.Collection 
    model: App.Animal 
    url: '/animals/' #returns json 

そして、これらの動物クラス:

App.Models.Animal extends Backbone.Model 

App.Models.Monkey extends App.Models.Animal 
    defaults:{type:'Monkey'} 

App.Models.Cat extends App.Models.Animal 
    defaults:{type:'Cat'} 

App.Models.Dog extends App.Models.Animal 
    defaults:{type:'Dog'} 

コレクションは私がモデルは、サブ分類モデル(猿、猫としてインスタンス化することにしたい(レコードがタイプ属性を含む)JSONで満たされている場合には、犬)であり、動物としてではない。どのようにこれを達成することができますか?

答えて

12

バックボーンdocumentationから:

コレクションは、モデルを返す関数で、この プロパティをオーバーライドすることで、多型のモデルを含めることができます。

var Library = Backbone.Collection.extend({ 

    model: function(attrs, options) { 
    if (condition) { 
     return new PublicDocument(attrs, options); 
    } else { 
     return new PrivateDocument(attrs, options); 
    } 
    } 

}); 
0

バックボーンコレクションの_prepareModelを上書きします。 newコレクションは、別の方法で定義されている場合、デフォルトモデルを使用してサブクラスを使用します。

class App.Collections.Animals extends Backbone.Collection 

model: App.Models.Animal 

_prepareModel: (attrs, options) -> 
    if attrs instanceof Backbone.Model 
    attrs.collection = @ 
    return attrs 

    options || (options = {}) 
    options.collection = @ 
    model_class = APP.Models[attrs.ntype] or this.model 
    model = new model_class(attrs, options) 
    if (!model._validate(attrs, options)) 
    false 
    else 
    model 
6

ソリューションは、(私はCoffeeScriptのを知らない、JSはご容赦)簡単です:

var SmartZoo = Backbone.Collection.extend({ 
    model: function (attrs, options) { 
     // This code assumes that the object looks something like '{ type: "Cat", ... }'. 
     switch (attrs.type) { 
      case 'Cat': 
       return new Cat(attrs, options); 
      case 'Dog': 
       return new Dog(attrs, options); 
      default: // Unknown subclass 
       return new Animal(attrs, options); 
     } 
    } 
}); 

あなたが持っている:

  1. からモデル内の属性を含めます作成するバックボーンモデルのタイプを推測することができます。この例では、私のオブジェクトには "type"という属性があり、その値はその値を表すBackbone型のフルネームです。実際のモデルインスタンスをコレクションに追加できるように、モデルをデフォルトに設定するか、モデルの初期化を行ってください。
  2. コレクションのmodelsプロパティを関数として定義します。この関数の最初のパラメータは、未処理のJSオブジェクト(渡された場合)またはBackboneモデルの属性オブジェクトになります。いずれにしても、このオブジェクトのプロパティとして型フィールドにアクセスできます。
  3. ロジックを実行して、タイプフィールドから適切なモデルを推論します。
  4. モデル関数から正しいモデルのインスタンスを返します。ここで

はアクションで、この多型のコレクションを示しているJSFiddleです:http://jsfiddle.net/FiddlerOnTheTarmac/uR2Sa/

+0

はジャスト)(場合コレクションは 'モデルの多くを持っている可能性がある場合ことに注意してください。 else if; elseは 'switch ' – seebiscuit

関連する問題