-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModel.js
100 lines (84 loc) · 2.86 KB
/
Model.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import Collection from './Collection.js';
/**
* A base Model class. Most other models are instances of this base Model.
* @memberof core
*/
class Model {
/**
* A utility function to define an array property on a class which ensures that the array cannot be overwritten. 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._
* @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) {
const collection = new Collection(ItemModel);
Object.defineProperty(object, propName, {
configurable: true,
enumerable: true,
get() {
return collection;
},
set(val) {
collection.length = 0;
collection.push(...val.map(item => new ItemModel(item)));
},
});
}
/**
* A utility function to define a property on a class which must always be an instance of a certain class._
* @param {Object} object The object to define the property on
* @param {String} propName The name of the property to define on the object
* @param {Function} ItemModel The class to use for this property. Every time this property is set, this model will be instantiated.
* @return {Object} Returns the original object with the new property added
*/
static defineModelProp(object, propName, ItemModel) {
let model;
Object.defineProperty(object, propName, {
configurable: true,
enumerable: true,
get() {
return model;
},
set(val) {
model = new ItemModel(val);
},
});
}
/**
* Create a "type" property on an object that is non-writable
* @param {Object} object The object to define the property on
* @param {String} type The value to use for the type
*/
static defineTypeProp(object, type) {
Object.defineProperty(object, `type`, {
configurable: true,
enumerable: true,
get() {
return type;
},
set() {}, // eslint-disable-line no-empty-function
});
}
/**
* A utility function that defines a property on a class that validates its value when set.
* @param {Object} object [description]
* @param {String} propName [description]
* @param {Function} validate [description]
*/
static defineValidatedProp(object, propName, validate) {
let value;
Object.defineProperty(object, propName, {
configurable: true,
enumerable: true,
get() {
return value;
},
set(val) {
if (val === undefined) return;
validate(val);
value = val;
},
});
}
}
export default Model;