-
Notifications
You must be signed in to change notification settings - Fork 0
/
js-data-collection-behavior.html
92 lines (79 loc) · 2.58 KB
/
js-data-collection-behavior.html
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
<link rel="import" href="../polymer/polymer.html">
<script type="text/javascript">
window.Elfy = window.Elfy || {};
/**
* @polymerBehavior Elfy.JSDataCollectionBehavior
*/
Elfy.JSDataCollectionBehavior = {
JSData: {
collectionName: null,
collectionQuery: null,
collections: null,
noNotify: false,
},
attached() {
this.async(function() {
this._loadData()
}.bind(this))
},
_loadFreshData(cls, collectionName, query) {
let collection = App.Store.getCollection(collectionName)
cls.findAll(query).then((records) => {
this[collectionName] = records
this._collectionLoaded(collectionName)
})
if (!this.JSData.noNotify) {
this._setupNotifyForCollection(collection, collectionName)
}
},
_loadData() {
let Store = App.Store
if (!this.JSData.collections) {
let collectionName = this.JSData.collectionName
let query = this.JSData.collectionQuery || {}
this._loadSingleCollection(Store, collectionName, query)
} else {
this.JSData.collections.forEach((c) => {
let collectionName = c.name
let query = c.query || {}
this._loadSingleCollection(Store, collectionName, query)
})
}
},
_loadSingleCollection(Store, collectionName, query) {
if (!collectionName) return
let collection = Store.getCollection(collectionName)
var self = this
Store.findAll(collectionName, query).then((records) => {
self._collectionLoaded(collectionName, records)
self.set(collectionName, records)
self[collectionName + 'Loaded'] = true
})
if (!this.JSData.noNotify) {
this._setupNotifyForCollection(collection, collectionName)
}
},
_setupNotifyForCollection(collection, collectionName) {
let onChangeNotifyPath = function(collection, collectionName) {
this[collectionName] = collection.getAll()
this.notifyPath(collectionName)
}.bind(this, collection, collectionName)
collection.on('all', onChangeNotifyPath)
let clearListener = function(source, event, handler) {
source.off(event, handler)
}.bind(collection, 'all', onChangeNotifyPath)
this._cleanUpFunctions || (this._cleanUpFunctions = [])
this._cleanUpFunctions.push(clearListener)
},
_clearListeners() {
this._cleanUpFunctions.forEach((cleanUpFunction) => {
cleanUpFunction()
})
},
_collectionLoaded(name, records) {
},
dettached() {
this._clearListeners()
}
}
</script>