Skip to content

Commit be46388

Browse files
committed
refactored set() to be more efficient
no longer does conversion from attribute path back to string back to attribute path, and doesn't need to loop if the single-attribute syntax is use.
1 parent bb66b84 commit be46388

File tree

1 file changed

+23
-21
lines changed

1 file changed

+23
-21
lines changed

backbone-nested.js

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -45,31 +45,25 @@
4545
},
4646

4747
set: function(key, value, opts){
48-
// if it's an attribute path, convert back to string
49-
if (_.isArray(key)) {
50-
key = Backbone.NestedModel.createAttrStr(key);
51-
}
48+
var newAttrs = Backbone.NestedModel.deepClone(this.attributes);
5249

53-
var attrs;
54-
// check that it's an object, or null/undefined
55-
if (_.isObject(key) || key == null) {
56-
attrs = key;
57-
opts = value;
58-
} else {
59-
// Backbone 0.9.0+ syntax - `model.set(key, val)`
60-
attrs = {};
61-
attrs[key] = value;
50+
if (_.isString(key)) {
51+
// Backbone 0.9.0+ syntax: `model.set(key, val)` - convert the key to an attribute path
52+
key = Backbone.NestedModel.attrPath(key);
6253
}
63-
opts = opts || {};
6454

65-
var newAttrs = Backbone.NestedModel.deepClone(this.attributes),
66-
attrVal, attrPath, attrObj;
67-
68-
for (var attrStr in attrs){
69-
attrPath = Backbone.NestedModel.attrPath(attrStr);
70-
attrObj = Backbone.NestedModel.createAttrObj(attrPath, attrs[attrStr]);
55+
if (_.isArray(key)) {
56+
// attribute path
57+
this._mergeAttr(newAttrs, key, value, opts);
58+
} else { // it's an Object
59+
opts = value;
60+
var attrs = key,
61+
attrPath;
7162

72-
this._mergeAttrs(newAttrs, attrObj, opts);
63+
for (var attrStr in attrs){
64+
attrPath = Backbone.NestedModel.attrPath(attrStr);
65+
this._mergeAttr(newAttrs, attrPath, attrs[attrStr], opts);
66+
}
7367
}
7468

7569
return Backbone.NestedModel.__super__.set.call(this, newAttrs, opts);
@@ -121,7 +115,15 @@
121115

122116
// private
123117

118+
// note: modifies `newAttrs`
119+
_mergeAttr: function(newAttrs, attrPath, value, opts){
120+
var attrObj = Backbone.NestedModel.createAttrObj(attrPath, value);
121+
this._mergeAttrs(newAttrs, attrObj, opts);
122+
},
123+
124+
// note: modifies `dest`
124125
_mergeAttrs: function(dest, source, opts, stack){
126+
opts = opts || {};
125127
stack = stack || [];
126128

127129
_.each(source, function(sourceVal, prop){

0 commit comments

Comments
 (0)