[Pkg-javascript-commits] [backbone] 72/211: Initial support for models with non-default id attribute names (MongoDB, CouchDB). Various tickets.

Jonas Smedegaard js at moszumanska.debian.org
Sat May 3 17:00:04 UTC 2014


This is an automated email from the git hooks/post-receive script.

js pushed a commit to tag 0.5.0
in repository backbone.

commit 1a9404cfe8f56f9b892d72b4fd2381bef6ee4f49
Author: Jeremy Ashkenas <jashkenas at gmail.com>
Date:   Mon Feb 7 13:59:52 2011 -0500

    Initial support for models with non-default id attribute names (MongoDB, CouchDB). Various tickets.
---
 backbone.js   | 8 ++++++--
 test/model.js | 9 +++++++++
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/backbone.js b/backbone.js
index 51c657a..6ee10c1 100644
--- a/backbone.js
+++ b/backbone.js
@@ -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);
diff --git a/test/model.js b/test/model.js
index ab62cd5..649ed67 100644
--- a/test/model.js
+++ b/test/model.js
@@ -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 : ''});

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/backbone.git



More information about the Pkg-javascript-commits mailing list