-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeyedFlatResultsController.js
66 lines (53 loc) · 1.96 KB
/
KeyedFlatResultsController.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
import _ from 'underscore';
const ResultsChangeInsert = 'INSERT';
const ResultsChangeUpdate = 'UPDATE';
const ResultsChangeDelete = 'DELETE';
export default class KeyedFlatResultsController {
constructor(args) {
this.willChangeContent = args.willChangeContent;
this.didChangeSection = args.didChangeSection; // todo
this.didChangeObject = args.didChangeObject;
this.didChangeContent = args.didChangeContent;
this.lastObjects = {};
}
newObjects(newObjects) {
//console.log(newObjects);
if (_.isEqual(newObjects, this.lastObjects)) {
return;
}
if (this.willChangeContent) {
this.willChangeContent();
}
// process additions
let oldKeys = Object.keys(this.lastObjects[0]);
let newKeys = Object.keys(newObjects[0]);
let addedKeys = newKeys.filter(x => oldKeys.indexOf(x) < 0);
if (this.didChangeObject) {
addedKeys.map((id) => {
this.didChangeObject(ResultsChangeInsert, newObjects[0][parseInt(id)]);
});
}
// process deletions
let deletedKeys = oldKeys.filter(x => newKeys.indexOf(x) < 0);
if (this.didChangeObject) {
deletedKeys.map((id) => {
this.didChangeObject(ResultsChangeInsert, this.lastObjects[0][parseInt(id)]);
});
}
// process updates
let existingKeys = oldKeys.filter(x => newKeys.indexOf(x) > -1);
if (this.didChangeObject) {
existingKeys.map((id) => {
let oldObj = this.lastObjects[0][parseInt(id)];
let newObj = newObjects[0][parseInt(id)];
if (!_.isEqual(oldObj, newObj)) {
this.didChangeObject(ResultsChangeUpdate, newObj);
}
});
}
if (this.didChangeContent) {
this.didChangeContent();
}
this.lastObjects = newObjects;
}
}