diff --git a/.eslintrc.yml b/.eslintrc.yml index f538db8..e0a0c0f 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -8,8 +8,8 @@ parserOptions: overrides: - files: - '*.test.js' - - '*.spec.js' rules: + max-classes-per-file: 'off' no-unused-expressions: 'off' env: browser: false diff --git a/src/core/Model.js b/src/core/Model.js index 493e6c5..b1c1833 100644 --- a/src/core/Model.js +++ b/src/core/Model.js @@ -4,6 +4,30 @@ */ class Model { + /** + * A utility function to define an array property on a class which ensures that each item in the array is an instance of the provided class/model whenever the property is set to a new array. This method does **not** prevent users from adding new items to the array which are not instances of the class. Use the Collection object to obtain this behavior. **NOTE:** _This method may only be called inside a class constructor. The private property (`#propName`) must also be defined on the class._ + * @param {Object} object The object to define the property on + * @param {String} propName The name of the property to define on the object + * @return {Object} Returns the original object with the new property added + */ + static defineArrayProp(object, propName, ItemModel) { + + Object.defineProperty(object, propName, { + configurable: true, + enumerable: true, + get() { + return this[`#${propName}`]; + }, + set(val) { + this[`#${propName}`] = val; + this[`#${propName}`].forEach((data, i, arr) => { + arr[i] = new ItemModel(data); // eslint-disable-line no-param-reassign + }); + }, + }); + + } + /** * A utility function to define a property on a class which must always be an instance of a certain class. **NOTE:** _This method may only be called inside a class constructor. The private property (`#propName`) must also be defined on the class._ * @param {Object} object The object to define the property on diff --git a/src/core/Model.test.js b/src/core/Model.test.js index d0bfd12..0fa41b3 100644 --- a/src/core/Model.test.js +++ b/src/core/Model.test.js @@ -5,13 +5,35 @@ chai.should(); describe(`Model`, () => { + class TestModel {} + it(`is the Model class`, () => { Model.name.should.equal(`Model`); }); - it(`defineModelProp`, () => { + it(`defineArrayProp`, () => { + + class TestObject { + + #testProp; + + constructor() { + Model.defineArrayProp(this, `testProp`, TestModel); + } - class TestModel {} + } + + const testObject = new TestObject; + const arr = [`a`, `b`]; + + testObject.testProp = arr; + + testObject.testProp.should.equal(arr); + testObject.testProp.forEach(item => item.should.be.instanceOf(TestModel)); + + }); + + it(`defineModelProp`, () => { class TestObject {