我正在使用带有主干的MongoDb / Lithium php框架。
我希望我的所有模型ID和IDAttribute与我的数据库文档ID相同(即'_id'/ mongoid)
问题:
这是模型类:
window.app.IHoliday = Backbone.Model.extend({
urlRoot: HOLIDAY_URL,
idAttribute: '_id',
id: '_id',
// Default attributes for the holiday.
defaults: {
},
initialize: function(props) {
},
});
这是 View 代码,在模型上调用fetch。文档的杂项作为隐藏输入(holiday_id)传递到此页面。
console.log('Holiday URL:' + HOLIDAY_URL );
var Holiday = new window.app.IHoliday({ _id: holiday_id });
console.log('HOLIDAY before fetch: \n' + JSON.stringify(Holiday));
Holiday.fetch(
{
success: function(){
//alert('Holiday fetched:' + JSON.stringify(Holiday));
console.log('HOLIDAY Fetched: \n' + JSON.stringify(Holiday));
console.log('Holiday name:' + Holiday.get('holiday_name'));
console.log('Holiday id:' + Holiday.id);
console.log('Holiday idAttribute:' + Holiday.idAttribute);
console.log('Holiday idAttribute:' + Holiday.get('idAttribute'));
}
});
firebug控制台的输出:
HOLIDAY before fetch:{"_id":"50bcaab24fbe3dfc1700000b"}
GET http://localhost:8080/li3/holidays/load/50bcaab24fbe3dfc1700000b 200 OK
HOLIDAY Fetched:
{"_id":"50bcaab24fbe3dfc1700000b","holiday_name":"eeeeeeeeeeeeeeeee","description":"","star_rating":"3","holiday_type":"family","rooms":"1","adults":"2","child":"0","emails":""}
Holiday name:eeeeeeeeeeeeeeeee
Holiday id:50bcaab24fbe3dfc1700000b
Holiday idAttribute:_id
Holiday idAttribute:undefined
编辑:
在注释掉模型类中id的条目之后,以下工作了...
window.app.IHoliday = Backbone.Model.extend({
urlRoot: HOLIDAY_URL,
//id: '_id',
idAttribute: '_id',
// Default attributes for the holiday.
defaults: {
},
initialize: function(props) {
},
最佳答案
idAttribute
包含将用作ID的类成员的名称。因此,如果使用idAttribute: '_id'
,Backbone将使用成员_id
作为类的ID。
如果要使用holiday_id
属性作为类IHoliday
的ID,则可以尝试:
window.app.IHoliday = Backbone.Model.extend({
urlRoot: HOLIDAY_URL,
idAttribute: 'holiday_id',
// Default attributes for the holiday.
defaults: {
},
initialize: function(props) {
},
});
var Holiday = new window.app.IHoliday({holiday_id : holiday_id });
Backbone 将使用
holiday_id
属性代替常规的id
属性。