Skip to content

Commit 4688a4e

Browse files
committed
To determine whether a newly created nest-level should be an object or
an array, we need to look at the next value in the path. Please run the tests without the patch in backbone-nested to see the bug in action. Thanks Closes #78
1 parent 01c6a2d commit 4688a4e

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

backbone-nested.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,10 +246,11 @@
246246
var fullPathLength = attrPath.length;
247247
var model = this;
248248

249-
Backbone.NestedModel.walkPath(newAttrs, attrPath, function(val, path){
249+
Backbone.NestedModel.walkPath(newAttrs, attrPath, function(val, path, next){
250250
var attr = _.last(path);
251251
var attrStr = Backbone.NestedModel.createAttrStr(path);
252252

253+
253254
// See if this is a new value being set
254255
var isNewValue = !_.isEqual(val[attr], newValue);
255256

@@ -301,7 +302,7 @@
301302

302303

303304
} else if (!val[attr]){
304-
if (_.isNumber(attr)){
305+
if (_.isNumber(next)){
305306
val[attr] = [];
306307
} else {
307308
val[attr] = {};
@@ -360,7 +361,7 @@
360361

361362
// walk through the child attributes
362363
for (var i = 0; i < attrPath.length; i++){
363-
callback.call(scope || this, val, attrPath.slice(0, i + 1));
364+
callback.call(scope || this, val, attrPath.slice(0, i + 1), attrPath[i + 1]);
364365

365366
childAttr = attrPath[i];
366367
val = val[childAttr];

test/nested-model.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,33 @@ $(document).ready(function() {
309309
deepEqual(json, doc.attributes);
310310
});
311311

312+
test("#toJSON() after an 1-N set using brackets", function() {
313+
var provider = new Klass({
314+
"fields[0].key": 'LOGIN'
315+
});
316+
equal(provider.get('fields[0].key'), 'LOGIN');
317+
318+
deepEqual(provider.toJSON(), {
319+
"fields": [{
320+
"key": "LOGIN"
321+
}]
322+
});
323+
});
324+
325+
test("#toJSON() after an 1-N set using dots", function() {
326+
var provider = new Klass({
327+
"fields.0.key": 'LOGIN2'
328+
});
329+
equal(provider.get('fields.0..key'), 'LOGIN2');
330+
331+
deepEqual(provider.toJSON(), {
332+
"fields": [{
333+
"key": "LOGIN2"
334+
}]
335+
});
336+
});
337+
338+
312339

313340
// ----- CHANGE EVENTS --------
314341

0 commit comments

Comments
 (0)