From 05786e881552aed472dd0998c1cea99bff577461 Mon Sep 17 00:00:00 2001 From: Bernhard Gschwantner Date: Fri, 16 Jan 2015 16:12:50 +0100 Subject: [PATCH] added basic support for setting instantiated children: Currently this copies the properties to a new child instance. Otherwise the listeners would have to be re-established. --- ampersand-state.js | 12 ++++++++++-- test/full.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/ampersand-state.js b/ampersand-state.js index 79a742e..1783e43 100644 --- a/ampersand-state.js +++ b/ampersand-state.js @@ -140,8 +140,16 @@ _.extend(Base.prototype, BBEvents, { if (!def) { - // if this is a child model or collection - if (this._children[attr] || this._collections[attr]) { + // if this is a child model + if (this._children[attr]) { + if (newVal instanceof this._children[attr]) { + // Get the raw attributes including the session values. + newVal = newVal.getAttributes({ props: true, session: true }, true); + } + this[attr].set(newVal, options); + continue; + // if this is a collection + } else if (this._collections[attr]) { this[attr].set(newVal, options); continue; } else if (extraProperties === 'ignore') { diff --git a/test/full.js b/test/full.js index e6eaab2..110c990 100644 --- a/test/full.js +++ b/test/full.js @@ -1046,6 +1046,46 @@ test('listens to child events', function (t) { first.firstChild.grandChild.name = 'Bob'; }); +test('instantiated children can be set', function (t) { + var Child = State.extend({ + props: { + id: 'string', + name: 'string' + } + }); + + var Parent = State.extend({ + props: { + id: 'string', + name: 'string' + }, + children: { + firstChild: Child, + secondChild: Child + } + }); + + var child = new Child({ + id: 'first-child', + name: 'first-child-name' + }); + + var parent = new Parent({ + id: 'child', + name: 'first-name', + firstChild: child, + secondChild: { + id: 'second-child', + name: 'second-child-name' + } + }); + + t.plan(2); + + t.equal(parent.firstChild.name, 'first-child-name', 'instantiated child should be directly accessible'); + t.equal(parent.secondChild.name, 'second-child-name', 'regular child should be directly accessible'); +}); + test('Should be able to declare derived properties that have nested deps', function (t) { var GrandChild = State.extend({ props: {