Skip to content

Commit

Permalink
Merge pull request #213 from kamilogorek/clear-with-values
Browse files Browse the repository at this point in the history
Allow clear() on props with values array. FIX #212
  • Loading branch information
pgilad committed Nov 5, 2015
2 parents f2f9b72 + d70bd70 commit 30d80a6
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
8 changes: 7 additions & 1 deletion ampersand-state.js
Expand Up @@ -191,6 +191,7 @@ assign(Base.prototype, Events, {
// If we are required but undefined, throw error.
// If we are null and are not allowing null, throw error
// If we have a defined type and the new type doesn't match, and we are not null, throw error.
// If we require specific value and new one is not one of them, throw error (unless it has default value or we're unsetting it with undefined).

if (newVal === undefined && def.required) {
throw new TypeError('Required property \'' + attr + '\' must be of type ' + def.type + '. Tried to set ' + newVal);
Expand All @@ -202,7 +203,12 @@ assign(Base.prototype, Events, {
throw new TypeError('Property \'' + attr + '\' must be of type ' + def.type + '. Tried to set ' + newVal);
}
if (def.values && !includes(def.values, newVal)) {
throw new TypeError('Property \'' + attr + '\' must be one of values: ' + def.values.join(', ') + '. Tried to set ' + newVal);
var defaultValue = result(def, 'default');
if (unset && defaultValue !== undefined) {
newVal = defaultValue;
} else if (!unset || (unset && newVal !== undefined)) {
throw new TypeError('Property \'' + attr + '\' must be one of values: ' + def.values.join(', ') + '. Tried to set ' + newVal);
}
}

hasChanged = !isEqual(currentVal, newVal, attr);
Expand Down
55 changes: 55 additions & 0 deletions test/basics.js
Expand Up @@ -1137,3 +1137,58 @@ test('#74 - ensure default array/object types are mutable', function (t) {
t.equal(s.anObject.foo, 'bar');
t.end();
});

test('unset on prop with values array - issue #144', function (t) {
var Model = State.extend({
props: {
stuff: {
type: 'string',
required: false,
values: ['a', 'b', 'c']
}
}
});
var model = new Model({ stuff: 'a' });
t.doesNotThrow(function () {
model.unset('stuff');
});
t.equal(model.stuff, undefined);
t.end();
});

test('unset on prop with values array and default - issue #144', function (t) {
var Model = State.extend({
props: {
stuff: {
type: 'string',
required: false,
values: ['a', 'b', 'c'],
default: 'c'
}
}
});
var model = new Model({ stuff: 'a' });
t.doesNotThrow(function () {
model.unset('stuff');
});
t.equal(model.stuff, 'c');
t.end();
});

test('clear including prop with values array - issue #144', function (t) {
var Model = State.extend({
props: {
stuff: {
type: 'string',
required: false,
values: ['a', 'b', 'c']
}
}
});
var model = new Model({ stuff: 'a' });
t.doesNotThrow(function () {
model.clear();
});
t.equal(model.stuff, undefined);
t.end();
});

0 comments on commit 30d80a6

Please sign in to comment.