diff --git a/ampersand-state.js b/ampersand-state.js index 5f587de..35573d1 100644 --- a/ampersand-state.js +++ b/ampersand-state.js @@ -114,6 +114,10 @@ _.extend(Base.prototype, BBEvents, { options = options || {}; + if (options.parse) { + attrs = this.parse(attrs, options); + } + if (!this._validate(attrs, options)) return false; // Extract attributes and options. diff --git a/test/full.js b/test/full.js index 52c6dd0..05cdc13 100644 --- a/test/full.js +++ b/test/full.js @@ -1542,74 +1542,31 @@ test('#68, #110 mixin props should not be deleted', function (t) { t.end(); }); -test('#114 setOnce allows values to be set once and only once', function (t) { - var Model = State.extend({ - props: { - x: { - type: 'string', - setOnce: true, - required: true, - } - } - }); - - var model = new Model({ x: 'foo' }); - - t.equal(model.x, 'foo'); - - t.throws(function () { - model.x = 'bar'; - }, /can only be set once/); - - t.end(); -}); - -test('#118 setOnce can be used with default string', function (t) { - var TimeRange = State.extend({ - props: { - timezone: { - type: 'string', - default: 'something that can only be set as the default', - setOnce: true - } - } - }); - - var tr = new TimeRange(); - - t.throws(function () { - tr.timezone = 'new thing'; - }, 'since it has a default, this should throw'); - - - var tr2; - - t.doesNotThrow(function () { - tr2 = new TimeRange({timezone: 'my thing'}); - }, 'if we set on init, should overwrite default'); - - t.throws(function () { - tr.timezone = 'new thing'; - }, 'should now fail since its been set'); - - var OtherTimeRange = State.extend({ +test('#106 #84 - set accepts options.parse', function (t) { + var me; + var Person = State.extend({ props: { - timezone: { - type: 'string', - setOnce: true - } + id: 'number', + name: 'string' + }, + parse: function (attrs) { + attrs.id = attrs.personID; + delete attrs.personID; + return attrs; } }); - tr = new OtherTimeRange(); + me = new Person(); + me.set({ personID: 123, name: 'Phil' }); + t.equal(me.id, undefined, 'does not parse attributes if not passed'); - t.doesNotThrow(function () { - tr.timezone = 'thing'; - }, 'should not throw first time'); + me = new Person(); + me.set({ personID: 123, name: 'Phil' },{ parse: false }); + t.equal(me.id, undefined, 'does not parse attributes if options.parse is false'); - t.throws(function () { - tr.timezone = 'other thing'; - }, 'throws second time'); + me = new Person(); + me.set({ personID: 123, name: 'Phil' },{ parse: true }); + t.equal(me.id, 123, 'parses attributes if options.parse is true'); t.end(); });