forked from unbug/codelf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseModel.js
More file actions
79 lines (66 loc) · 1.57 KB
/
BaseModel.js
File metadata and controls
79 lines (66 loc) · 1.57 KB
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
import EventEmitter from 'events';
class Mutation {
constructor(data) {
this._data = data;
this._serialize();
this.has = this.has.bind(this);
}
_serialize() {
Object.keys(this._data).forEach(key => {
this[key] = true;
});
}
get() {
return this._data;
}
has(fields) {
if (/string/i.test(typeof fields)) {
fields = fields.split(',');
}
if (Array.isArray(fields)) {
return fields.every((key) => {
key = key.trim();
return this[key];
});
}
return false;
}
}
class BaseModel extends EventEmitter {
constructor() {
super();
this.on('error', () => {});
this.setMaxListeners(99);
this._updateEventName = 'update';
this._data = {};
}
set(data) {
let prevData = Object.assign({}, this._data);
this._data = data || {};
this.notify(prevData, Object.assign({}, prevData, data, {isReset: true}));
}
get() {
return this._data;
}
create(data) {
let instance = Object.create(Object.getPrototypeOf(this));
instance._data = data;
return instance;
}
notify(prevData, mutationData) {
let data = Object.assign({}, this._data);
this.emit(this._updateEventName, data, prevData || data, new Mutation(mutationData));
}
update(data) {
let prevData = Object.assign({}, this._data);
Object.assign(this._data, data);
this.notify(prevData, data);
}
onUpdated(listener) {
this.on(this._updateEventName, listener);
}
offUpdated(listener) {
this.removeListener(this._updateEventName, listener);
}
}
export default BaseModel;