【发布时间】:2014-07-16 22:40:41
【问题描述】:
我在显示用户列表的页面上使用 Backbone.js、Marionette.js 和 Backbone-relational。每个用户都被标识为“待定”或“活动”。 “待定”用户是已收到加入(聚会)邀请但尚未接受的用户; “活跃”是那些已经确认的人。待处理用户列表由一个 API 调用获取,活动用户列表由另一个 API 调用获取。
所以情况是这样的:
一个用户,我们称他为“Miguel”,被提取到活跃用户的集合中。但是,如果将具有与 Miguel 相同 ID 的“待处理”用户提取到待处理用户集合中,则 Miguel 将收到属性“状态”:“待处理”。我可以验证 Miguel 没有被提取到(或传递给--的解析函数)待处理用户的集合中。
所以我想知道 Backbone 关系是否存在与模型 ID 有时相互匹配的两个集合的关系的问题。
举例说明:
如果活跃用户集合: { 编号:22, “名字”:“米格尔” }
和待处理用户的集合: { 编号:22, “名字”:“贝蒂”, “状态”:“待定” }
然后米格尔最终看起来像:{ 编号:22, '名字':'米格尔', “状态”:“待定” }
这是我的模型和集合的代码:
/**
* "NV" is a base class we created for this application. It handles .save(), .toPatchJSON(), tracks changed attrs and other such functions.
*/
/**
* This is the collection of "pending" users
*/
var PendingUsers = NV.Collection.extend({
model: User,
initialize: function(models, options) {
Backbone.Collection.prototype.initialize.call(this,models,options);
this.org = options.org;
},
url: function() {
return "/api/organization/" + this.org.get("Id") + "/invites";
},
parse: function(resp, options) {
// "Miguel" never shows up in this function yet obtains the "Pending" Status property.
return _.map(resp, function(invite) {
return {
Id: invite.Id,
FirstName: invite.FirstName,
LastName: invite.LastName,
Email: invite.Email,
InvitationTime: invite.InvitationTime + "+00:00",
Status: 'Pending'
}
});
}
});
/**
* This is the collection of "active" users
*/
var ActiveUsers = NV.Collection.extend({
model: User,
initialize: function(models, options) {
Backbone.Collection.prototype.initialize.call(this,models,options);
this.org = options.org;
},
url: function() {
return "/api/organization/" + this.org.get("Id") + "/users";
}
});
/**
* The collections of active and pending users are relations of the "Organization" model. This is what's passed to the View that renders the list of users.
*/
var Organization = NV.Model.extend({
defaults: {
Name: ''
},
relations: [
{
type: Backbone.HasMany,
key: 'Users',
relatedModel: User,
collectionType: ActiveUsers,
collectionOptions: function(org) {
return {'org': org };
}
},
{
type: Backbone.HasMany,
key: 'InvitedUsers',
relatedModel: User,
collectionType: PendingUsers,
collectionOptions: function(org) {
return {'org': org };
}
}
],
urlRoot: "/api/organization"
});
return Organization;
/**
* Both pending and active collections build from the User model, so here it is
*/
var User = NV.Model.extend({
schema: {
Name: 'Text',
Email: { validators: ['required', 'email'] },
password: 'Password'
},
defaults: {
FirstName: '',
LastName: '',
Email: ''
},
fetch: function(options) {
this.me = options.me || false;
NV.Model.prototype.fetch.call(this,options);
},
avatar: function(options){
return "/api/user/" + this.get("Id") + "/avatar";
},
url: function() {
if (this.me) return "/api/user/me";
return "/api/user/" + this.get("Id");
}
});
return User;
如果我未能提供重要信息,请告诉我。在这个问题!谢谢!
【问题讨论】:
标签: backbone.js backbone-relational