From 331cb8bedea21e61128056608714d7dbd117db86 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Mon, 20 Dec 2010 23:00:51 -0500 Subject: [PATCH] Allowing Model#defaults to be a function as well as a hash. --- backbone.js | 6 +++++- index.html | 8 ++++---- test/model.js | 11 +++++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/backbone.js b/backbone.js index 8067adbc..84944008 100644 --- a/backbone.js +++ b/backbone.js @@ -115,8 +115,12 @@ // Create a new model, with defined attributes. A client id (`cid`) // is automatically generated and assigned for you. Backbone.Model = function(attributes, options) { + var defaults; attributes || (attributes = {}); - if (this.defaults) attributes = _.extend({}, this.defaults, attributes); + if (defaults = this.defaults) { + if (_.isFunction(defaults)) defaults = defaults(); + attributes = _.extend({}, defaults, attributes); + } this.attributes = {}; this._escapedAttributes = {}; this.cid = _.uniqueId('c'); diff --git a/index.html b/index.html index 8b1353dc..9316a3df 100644 --- a/index.html +++ b/index.html @@ -642,11 +642,11 @@ if (note.has("title")) {

- defaultsmodel.defaults + defaultsmodel.defaults or model.defaults()
- The defaults hash can be used to specify the default attributes - for your model. When creating an instance of the model, any unspecified - attributes will be set to their default value. + The defaults hash (or function) can be used to specify the default + attributes for your model. When creating an instance of the model, + any unspecified attributes will be set to their default value.

diff --git a/test/model.js b/test/model.js
index b90f77d5..5a313dc9 100644
--- a/test/model.js
+++ b/test/model.js
@@ -172,6 +172,17 @@ $(document).ready(function() {
     var model = new Defaulted({two: null});
     equals(model.get('one'), 1);
     equals(model.get('two'), null);
+    Defaulted = Backbone.Model.extend({
+      defaults: function() {
+        return {
+          "one": 3,
+          "two": 4
+        };
+      }
+    });
+    var model = new Defaulted({two: null});
+    equals(model.get('one'), 3);
+    equals(model.get('two'), null);
   });
 
   test("Model: change, hasChanged, changedAttributes, previous, previousAttributes", function() {