-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunk.html
More file actions
313 lines (245 loc) · 9.89 KB
/
funk.html
File metadata and controls
313 lines (245 loc) · 9.89 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../yarn-state-behavior/yarn-state-behavior.html">
<link rel="import" href="reflux-core.html">
<script>
var Funk = Funk || {};
(function() {
var Reflux = Funk.Reflux = require('reflux-core');
/**
This behavior turns a Polymer component into a store that can subscribe to Reflux actions and publish state changes to your Polymer views.
Each property with `{ notify: true }` is mirrored on to `state[storeName]`, which is available to any of your views that have the `Funk.ViewBehavior` (simply an alias for [`YarnBehaviors.StateBehavior`](https://github.com/yarn-co/yarn-state-behavior)).
Not only is the store mirrored on to `state[storeName]`, but data-binding is also perfectly preserved. So your views can subscribe to changes to your stores using all the familiar means: computed properties, observers, and one-way DOM-binding (i.e. `[[state.myStore.someProp]]`), etc.
_**Note:** Be sure not to use two-way binding with `state` to keep that funky, fluxy one-directional data-flow!_
Aside from providing several helper methods, this behavior also imparts all of Reflux's listening methods to your store component, including `hasListener()`, `listenToMany()`, `validateListening()`, `listenTo()`, `stopListeningTo()`, `stopListeningToAll()`, `joinTrailing()`, `joinLeading()`, `joinConcat()`, and `joinStrict()`.
A note on timing: stores may be initialized all the way through the `attached()` Polymer lifecycle hook– `state[myStore]` comes into effect _directly after_ the `attached()` hook (using microtask timing). This is consistent with the timing with which Polymer's computed properties resolve.
@polymerBehavior Funk.StoreBehavior
@demo demo/index.html
*/
Funk.StoreBehaviorImpl = {
properties: {
/**
* The name of the store.
* This name will be used as the key that gets placed on
* `state` to reference the store, e.g. `state[storeName]`
* can be used throughout your views to reference this
* store (on all `Funk.ViewBehavior` elements).
*/
storeName: {
type: String,
readOnly: true
},
/**
* Behaves identically to Reflux's [listenables](https://github.com/reflux/refluxjs#the-listenables-shorthand).
*/
funkListenables: {
type: Array,
value: function() {
return [];
}
}
},
ready: function() {
if (!this.storeName) {
throw new Error('Store must have a name.');
}
// Hook-up listenables
var listenables = [].concat(this.funkListenables);
for (var i = 0; i < listenables.length; i++) {
this.listenToMany(listenables[i]);
}
},
attached: function() {
// Wrap binding logic in async to allow computed bindings, etc. to settle
this.async(function() {
// Init storage spot
this.state[this.storeName] = {};
// Link store names to state
var notifies;
var propName;
var properties = Object.keys(this.properties);
for (var i = 0; i < properties.length; i++) {
propName = properties[i];
notifies = this.properties[propName].notify;
if (propName !== 'storeName' && propName !== 'state' && notifies) {
// Set state and link paths. Path linking takes care of passing
// along deep changes, but not shallow ones.
// E.g. passes along `someProp.length` but not `someProp`
this.set(['state', this.storeName, propName], this[propName]);
this.linkPaths('state.' + this.storeName + '.' + propName, propName);
// Now take care of shallow changes by simply listening, ignoring
// changes to deep paths.
var changedEvent = Polymer.CaseMap.camelToDashCase(propName) + '-changed';
var changedListener = function(prop, e) {
if (!e.detail.path) {
this.set(['state', this.storeName, prop], this[prop]);
}
};
this.addEventListener(changedEvent, changedListener.bind(this, propName));
}
}
});
}
};
/**
This behavior provides utilities to work with Funk collections.
A collection is simply an id-keyed object of the form,
`{ 22: {...}, 144: {...}, 3: {...} }`.
@polymerBehavior Funk.CollectionBehavior
@demo demo/index.html
*/
Funk.CollectionBehavior = {
/**
* If you'd like a property to mirror one of the items
* in a collection, you would use `deriveItem()`.
*
* Ex.
* ```js
* this.collection = { 22: {...}, 144: {...}, 3: { val: 'fluxy!' } };
* this.deriveItem('someItem', 'collection', 3);
* this.someItem; // { val: 'fluxy!' }
*
* // This will notify anyone observing someItem
* this.set('collection.3.val', 'funky!');
* this.someItem; // { val: 'funky!' }
* ```
*/
deriveItem: function(prop, collection, id) {
this.set(prop, this.get([collection, id]));
// Implicitly unlinks any previously linked paths
this.linkPaths(prop, collection + '.' + id);
},
/**
* If you'd like a property to mirror a fixed list of the
* items in a collection as an array, you would use `deriveList()`.
*
* Ex.
* ```js
* this.collection = { 22: {...}, 144: { val: 'gross!' }, 3: { val: 'fluxy!' } };
* this.deriveList('someList', 'collection', [144, 3]);
* this.someList; // [{ val: 'gross!' }, { val: 'fluxy!' }]
*
* // This will notify anyone observing someList.#0
* this.set('collection.144.val', 'mmm!');
* this.someList; // [{ val: 'mmm!' }, { val: 'fluxy!' }]
* ```
*/
deriveList: function(prop, collection, ids) {
// Unlink existing paths
var currentList = this.get(prop) || [];
for (var i = 0; i < currentList.length; i++) {
this.unlinkPaths(prop + '.#' + i);
}
// Create new list, linking paths
var list = [];
var id;
for (var j = 0; j < ids.length; j++) {
id = ids[j];
list.push(this.get([collection, id]));
this.linkPaths(prop + '.#' + j, collection + '.' + id);
}
// Finally set list
this.set(prop, list);
},
/**
* If you'd like a property to mirror a dynamic list of the
* items in a collection as an array, you would use `deriveDynList()`.
*
* The dynamic list `dyn` must be a notifying property.
*
* Ex.
* ```js
* this.friendIds = [3, 5, 8, 13];
* this.deriveDynList('friends', 'usersCollection', 'friendIds');
* // Notifies friends.splices
* this.push('friendIds', 21);
* // Notifies friends.#4.name
* this.set(['usersCollection', 21, 'name'], 'Copernicus');
* ```
*/
deriveDynList: function(prop, collection, dyn) {
var self = this;
// Ensure the dynamic ids list is notifying,
// hopefully only until Polymer/polymer#3460
if (dyn.indexOf('.') === -1 && !this.getPropertyInfo(dyn).notify) {
throw new Error('Property "' + dyn + '" must be notifying ' +
'in order to be used as a dynamic list.');
}
var changedEvent = Polymer.CaseMap.camelToDashCase(dyn) + '-changed';
var changedListener = function(e) {
var dynIds = this.get(dyn);
// Complete reset
if (!e.detail.path) {
return this.deriveList(prop, collection, dynIds);
}
if (e.detail.path === dyn + '.splices') {
var splices = e.detail.value.indexSplices;
if (!splices.length) {
return;
}
// Currently cannot apply multiple splices one at a time,
// see Polymer/polymer#3578
if (splices.length > 1) {
return this.deriveList(prop, collection, dynIds);
}
var start = splices[0].index;
var numAdded = splices[0].addedCount;
var numRemoved = splices[0].removed.length;
var propValue = this.get(prop);
var addedObjs = dynIds.slice(start, start + numAdded).map(function(id) {
return self.get([collection, id]);
});
// Make the actual splice!
this.splice.apply(this, [prop, start, numRemoved].concat(addedObjs));
// Link as few paths as necessary
var end = (numAdded === numRemoved) ? start + numAdded : propValue.length;
for (var i = start; i < end; ++i) {
this.linkPaths(prop + '.#' + i, collection + '.' + dynIds[i]);
}
// Remove vestigial links
var propLength = propValue.length;
var deadTail = numRemoved - numAdded;
for (var j = propLength; j < propLength + deadTail; ++j) {
this.unlinkPaths(prop + '.#' + j);
}
}
};
this.deriveList(prop, collection, this.get(dyn) || []);
this.addEventListener(changedEvent, changedListener);
},
/**
* Converts an array of the format `[{ id: 1 }, { id: 38 }]`
* to an object of the format `{ 1: { id: 1 }, 38: { id: 38 } }`
* (a Funk collection).
*
* This is intended to be used to facilitate collections
* used by `deriveItem()` and `deriveList()`.
*
* The second argument `keyName` may override the keying field-name,
* and defaults to `'id'`.
*/
arrayToCollection: function(list, keyName) {
keyName = keyName || 'id';
var obj = {};
for (var i = 0; i < list.length; i++) {
obj[list[i][keyName]] = list[i];
}
return obj;
}
};
/** @polymerBehavior */
Funk.StoreBehavior = [
YarnBehaviors.StateBehavior,
Reflux.ListenerMethods,
Funk.CollectionBehavior,
Funk.StoreBehaviorImpl
];
/**
An alias of [YarnBehaviors.StateBehavior](https://github.com/yarn-co/yarn-state-behavior)
@polymerBehavior Funk.ViewBehavior
@demo demo/index.html
*/
Funk.ViewBehavior = [
YarnBehaviors.StateBehavior
];
})();
</script>