多态模型的骨干集 [英] Backbone Collection of polymorphic Models
本文介绍了多态模型的骨干集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有动物的集合。
App.Collections.Animals延伸Backbone.Collection
型号:App.Animal
网址:'/动物/'#returns JSON
和这些动物类:
App.Models.Animal延伸Backbone.ModelApp.Models.Monkey延伸App.Models.Animal
默认值:{类型:'猴子'}App.Models.Cat延伸App.Models.Animal
默认值:{类型:'猫'}App.Models.Dog延伸App.Models.Animal
默认值:{类型:'狗'}
当收集充满了JSON(记录包含的键入的属性)我想模型实例化为子类模型(猴子,猫,狗),而不是动物。你怎么能做到这一点?
解决方案
从主干文档:
一个集合也可以通过重写这个包含多态模型
财产返回一个模型的函数。
块引用>VAR库= Backbone.Collection.extend({ 型号:功能(ATTRS,期权){
如果(条件){
返回新PublicDocument(ATTRS,期权);
}其他{
返回新PrivateDocument(ATTRS,期权);
}
}});I have a collection of Animals.
App.Collections.Animals extends Backbone.Collection model: App.Animal url: '/animals/' #returns json
And these animal classes:
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'}
When collection is filled with JSON (records contain the type attribute) I want models to be instantiated as sub-classed models (Monkey,Cat,Dog) and not as Animal. How can you achieve this?
解决方案From Backbone documentation:
A collection can also contain polymorphic models by overriding this property with a function that returns a model.
var Library = Backbone.Collection.extend({ model: function(attrs, options) { if (condition) { return new PublicDocument(attrs, options); } else { return new PrivateDocument(attrs, options); } } });
这篇关于多态模型的骨干集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文