Initial support for models with non-default id attribute names (MongoDB, CouchDB). Various tickets.

This commit is contained in:
Jeremy Ashkenas
2011-02-07 13:59:52 -05:00
parent d04bf67b21
commit 1a9404cfe8
2 changed files with 15 additions and 2 deletions

View File

@@ -141,6 +141,10 @@
// Has the item been changed since the last `"change"` event?
_changed : false,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute : 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize : function(){},
@@ -183,7 +187,7 @@
if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;
// Check for changes of `id`.
if ('id' in attrs) this.id = attrs.id;
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// Update attributes.
for (var attr in attrs) {
@@ -215,7 +219,7 @@
// Remove the attribute.
delete this.attributes[attr];
delete this._escapedAttributes[attr];
if (attr == 'id') delete this.id;
if (attr == this.idAttribute) delete this.id;
this._changed = true;
if (!options.silent) {
this.trigger('change:' + attr, this, void 0, options);

View File

@@ -152,6 +152,15 @@ $(document).ready(function() {
equals(a.id, undefined, "Unsetting the id should remove the id property.");
});
test("Model: using a non-default id attribute.", function() {
var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
equals(model.get('id'), 'eye-dee');
equals(model.id, 25);
model.unset('_id');
equals(model.id, undefined);
});
test("Model: set an empty string", function() {
var model = new Backbone.Model({name : "Model"});
model.set({name : ''});