我正在尝试找到一种使用requirejs使用骨架 - 权利的子模型的方法,其中subsodels与SuperModel不同。
。例如:
// app.js
define(function() {
var app = {};
var app.ns = {};
Backbone.Relational.store.addModelScope(app.ns);
});
// Classroom/Person.js
define(["app", "./Student", "./Professor"], function(app) {
app.ns.Classroom.Person = Backbone.RelationalModel.extend({
subModelTypes: {
'Student': 'Classroom.Student'
'Professor': 'Classroom.Professor'
},
alertHello: function() {}
});
return app.ns.Classroom.Person;
});
// Classroom/Student.js
define(["require", "app", "./Person"], function(require, app) {
app.ns.Classroom.Student = require("./Person").extend({
alertHello: function() {
alert("Hello, I am student " + this.get("name"));
}
});
return app.ns.Classroom.Student;
});
// Classroom/PersonCollection.js
define(["app", "./Person"], function (app, Person) {
app.ns.Classroom.PersonCollection = Backbone.Collection.extend({
model: Person
});
});
// alertPeople.js
define(["Classroom/PersonCollection"], function(PersonCollection) {
var people = PersonCollection([{"name": "Bob", "type": "Person"}]);
people.each(function(person) {
person.alertHello();
});
});
当我执行AlertPeople.js时,我希望"您好,我是学生鲍勃"的警报,但是由于我的循环依赖性,我会遇到此错误:Uncaught Error: Module name "Classroom/Person" has not been loaded yet for context: _
。有什么可能解决这个问题?
我的下一个问题可能可能伴随着骨干关系的范围。在我的app.js文件中,我添加了范围的app.ns部分,并确保我的所有模型均在app.ns对象中定义。我这样做是这样,当我定义子模型时,它实际上可以引用子模型,但是我不确定这是否会起作用,因为我无法克服循环依赖性问题。
任何帮助将不胜感激。谢谢!
我最终解决了问题,希望这对其他人有帮助。
首先,我将代码修改为以下内容:
// app.js
define(function() {
var app = {};
var app.ns = {};
Backbone.Relational.store.addModelScope(app.ns);
});
// Classroom/Person.js
define(["app"], function(app) {
app.ns.Classroom.Person = Backbone.RelationalModel.extend({
subModelTypes: {
'Student': 'Classroom.Student'
'Professor': 'Classroom.Professor'
},
alertHello: function() {}
});
return app.ns.Classroom.Person;
});
// Classroom/Student.js
define(["app", "./Person"], function(app, Person) {
app.ns.Classroom.Student = Person.extend({
alertHello: function() {
alert("Hello, I am student " + this.get("name"));
}
});
return app.ns.Classroom.Student;
});
// Classroom/PersonCollection.js
define(["app", "./Person", "./Student", "./Professor"], function (app, Person) {
app.ns.Classroom.PersonCollection = Backbone.Collection.extend({
model: Person
});
});
// alertPeople.js
define(["Classroom/PersonCollection"], function(PersonCollection) {
var people = PersonCollection([{"name": "Bob", "type": "Person"}]);
people.each(function(person) {
person.alertHello();
});
});
我的更改包括删除课堂/person.js文件中的学生和教授依赖项,然后将其移至课堂/personcollection.js文件中。
之后,我遇到了一个带有骨架 - 权利的错误,addModelscope在suddModelscope上有一个带子模型和名称空间的错误,但是我对其进行了修复并提出了一个拉请:https://github.com/pauluithol/backbone-relational/pull/211,已被接受。
可以在https://github.com/andrewferk/backbone-relations-submodels上找到一个更完整的示例。