Skip to content

Commit

Permalink
Allow passing parse: true to set
Browse files Browse the repository at this point in the history
  • Loading branch information
jackboberg committed Feb 25, 2015
1 parent 8264fff commit 11e0835
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 62 deletions.
4 changes: 4 additions & 0 deletions ampersand-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
81 changes: 19 additions & 62 deletions test/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

0 comments on commit 11e0835

Please sign in to comment.