我正在尝试找到一种方法来使用带有RequireJS的Backbone关系子模型,其中子模型与超级模型位于不同的文件中。
例如:
// 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时,我希望收到“Hello,我是学生Bob”的警告,但由于我的循环依赖性,我得到了这个错误:Uncaught Error: Module name "Classroom/Person" has not been loaded yet for context: _
。什么是解决这个问题的可能解决方案?
我的下一个问题可能与Backbone-relational的范围有关。在我的app.js文件中,我添加了app.ns作为范围的一部分,并确保我的所有模型都在app.ns对象中定义。我这样做,所以当我定义我的subModelTypes时,它实际上可以引用子模型,但我不确定这是否可行,因为我无法通过循环依赖问题。
非常感谢任何帮助。谢谢!
答案 0 :(得分:5)
我最终解决了这个问题,我希望将来可以帮助其他人。
首先,我将代码修改为以下内容:
// 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();
});
});
我的更改包括删除Classroom / Person.js文件中的Student和Professor依赖项,并将它们移到Classroom / PersonCollection.js文件中。
在此之后,我遇到了一个关于Backbone-relational的bug,其中addModelScope有一个子模型和命名空间的bug,但我修复了它并发出了一个拉取请求:https://github.com/PaulUithol/Backbone-relational/pull/211,已被接受。
可以在https://github.com/andrewferk/backbone-relational-submodels找到更完整的示例。