mirror of
https://github.com/jashkenas/backbone.git
synced 2026-01-25 14:57:55 -05:00
Allowing Model#defaults to be a function as well as a hash.
This commit is contained in:
@@ -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');
|
||||
|
||||
@@ -642,11 +642,11 @@ if (note.has("title")) {
|
||||
</p>
|
||||
|
||||
<p id="Model-defaults">
|
||||
<b class="header">defaults</b><code>model.defaults</code>
|
||||
<b class="header">defaults</b><code>model.defaults or model.defaults()</code>
|
||||
<br />
|
||||
The <b>defaults</b> 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 <b>defaults</b> 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.
|
||||
</p>
|
||||
|
||||
<pre class="runnable">
|
||||
|
||||
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user