当我尝试在牵线木偶模块中创建子模型时,我遇到了Backbone-Relational的这个小问题。遵循主干关系文档我有:
Mammal = Backbone.RelationalModel.extend({
subModelTypes: {
'primate': 'Primate',
'carnivore': 'Carnivore'
}
});
Primate = Mammal.extend();
Carnivore = Mammal.extend();
MammalCollection = Backbone.Collection.extend({
model: Mammal
});
// Create a collection that contains a 'Primate' and a 'Carnivore'.
var mammals = new MammalCollection([
{ id: 3, species: 'chimp', type: 'primate' },
{ id: 5, species: 'panther', type: 'carnivore' }
]);
var chimp = mammals.get( 3 );
alert( 'chimp is a mammal? ' + ( chimp instanceof Mammal ) + '\n' +
'chimp is a carnivore? ' + ( chimp instanceof Carnivore ) + '\n' +
'chimp is a primate? ' + ( chimp instanceof Primate ) );
这在jsfiddle以及我的结尾完全正常。黑猩猩是哺乳动物和灵长类动物的一个例子。当这个代码在Marionette模块中运行时我的问题就开始了:
define(
[
"app",
"backbone-relational",
],
function(ManagerApp){
ManagerApp.module("Entities", function (Entities, ManagerApp, Backbone, Marionette, $, _) {
var Mammal = Backbone.RelationalModel.extend({
subModelTypes: {
'primate': 'Primate',
'carnivore': 'Carnivore'
}
});
var Primate = Mammal.extend();
var Carnivore = Mammal.extend();
var MammalCollection = Backbone.Collection.extend({
model: Mammal
});
// Create a collection that contains a 'Primate' and a 'Carnivore'.
var mammals = new MammalCollection([
{ id: 3, species: 'chimp', type: 'primate' },
{ id: 5, species: 'panther', type: 'carnivore' }
]);
var chimp = mammals.get( 3 );
alert( 'chimp is an animal? ' + ( chimp instanceof Mammal ) + '\n' +
'chimp is a carnivore? ' + ( chimp instanceof Carnivore ) + '\n' +
'chimp is a primate? ' + ( chimp instanceof Primate ) );
});
})
在这种情况下,我对哺乳动物的黑猩猩实例感到满意,但对灵长类动物和食肉动物却是假的。我意识到我的所有模型都应该附加到实体,但这也不起作用,我想测试最简单的场景。
为什么没有创建正确的子模型?