-
Notifications
You must be signed in to change notification settings - Fork 2k
/
notify-path.html
494 lines (465 loc) · 17.9 KB
/
notify-path.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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../lib/case-map.html">
<script>
/**
* Changes to an object sub-field (aka "path") via a binding
* (e.g. `<x-foo value="{{item.subfield}}"`) will notify other elements bound to
* the same object automatically.
*
* When modifying a sub-field of an object imperatively
* (e.g. `this.item.subfield = 42`), in order to have the new value propagated
* to other elements, a special `set(path, value)` API is provided.
* `set` sets the object field at the path specified, and then notifies the
* binding system so that other elements bound to the same path will update.
*
* Example:
*
* Polymer({
*
* is: 'x-date',
*
* properties: {
* date: {
* type: Object,
* notify: true
* }
* },
*
* attached: function() {
* this.date = {};
* setInterval(function() {
* var d = new Date();
* // Required to notify elements bound to date of changes to sub-fields
* // this.date.seconds = d.getSeconds(); <-- Will not notify
* this.set('date.seconds', d.getSeconds());
* this.set('date.minutes', d.getMinutes());
* this.set('date.hours', d.getHours() % 12);
* }.bind(this), 1000);
* }
*
* });
*
* Allows bindings to `date` sub-fields to update on changes:
*
* <x-date date="{{date}}"></x-date>
*
* Hour: <span>{{date.hours}}</span>
* Min: <span>{{date.minutes}}</span>
* Sec: <span>{{date.seconds}}</span>
*
* @class data feature: path notification
*/
(function() {
// Using strict here to ensure fast argument manipulation in array methods
'use strict';
Polymer.Base._addFeature({
/**
* Notify that a path has changed. For example:
*
* this.item.user.name = 'Bob';
* this.notifyPath('item.user.name', this.item.user.name);
*
* @param {string} path Path that should be notified.
* @param {*} value Value of the specified path.
* @param {boolean=} fromAbove When true, specifies that the change came
* from above this element and thus upward notification is not
* necessary.
* @return {boolean} Returns true if notification actually took place,
* based on a dirty check of whether the new value was already known.
*/
notifyPath: function(path, value, fromAbove) {
var old = this._propertySetter(path, value);
// manual dirty checking for now...
// NaN is always not equal to itself,
// if old and value are both NaN we treat them as equal
// x === x is 10x faster, and equivalent to !isNaN(x)
if (old !== value && (old === old || value === value)) {
// console.group((this.localName || this.dataHost.id + '-' + this.dataHost.dataHost.index) + '#' + (this.id || this.index) + ' ' + path, value);
// Take path effects at this level for exact path matches,
// and notify down for any bindings to a subset of this path
this._pathEffector(path, value);
// Send event to notify the path change upwards
// Optimization: don't notify up if we know the notification
// is coming from above already (avoid wasted event dispatch)
if (!fromAbove) {
// TODO(sorvell): should only notify if notify: true?
this._notifyPath(path, value);
}
// console.groupEnd((this.localName || this.dataHost.id + '-' + this.dataHost.dataHost.index) + '#' + (this.id || this.index) + ' ' + path, value);
return true;
}
},
/**
Converts a path to an array of path parts. A path may be specified
as a dotted string or an array of one or more dotted strings (or numbers,
for number-valued keys).
*/
_getPathParts: function(path) {
if (Array.isArray(path)) {
var parts = [];
for (var i=0; i<path.length; i++) {
var args = path[i].toString().split('.');
for (var j=0; j<args.length; j++) {
parts.push(args[j]);
}
}
return parts;
} else {
return path.toString().split('.');
}
},
/**
* Convienence method for setting a value to a path and notifying any
* elements bound to the same path.
*
* Note, if any part in the path except for the last is undefined,
* this method does nothing (this method does not throw when
* dereferencing undefined paths).
*
* @method set
* @param {(string|Array<(string|number)>)} path Path to the value
* to read. The path may be specified as a string (e.g. `foo.bar.baz`)
* or an array of path parts (e.g. `['foo.bar', 'baz']`). Note that
* bracketed expressions are not supported; string-based path parts
* *must* be separated by dots. Note that when dereferencing array
* indicies, the index may be used as a dotted part directly
* (e.g. `users.12.name` or `['users', 12, 'name']`).
* @param {*} value Value to set at the specified path.
* @param {Object=} root Root object from which the path is evaluated.
*/
set: function(path, value, root) {
var prop = root || this;
var parts = this._getPathParts(path);
var array;
var last = parts[parts.length-1];
if (parts.length > 1) {
for (var i=0; i<parts.length-1; i++) {
var part = parts[i];
prop = prop[part];
if (array && (parseInt(part) == part)) {
parts[i] = Polymer.Collection.get(array).getKey(prop);
}
if (!prop) {
return;
}
array = Array.isArray(prop) ? prop : null;
}
if (array && (parseInt(last) == last)) {
var coll = Polymer.Collection.get(array);
var old = prop[last];
var key = coll.getKey(old);
parts[i] = key;
coll.setItem(key, value);
}
prop[last] = value;
if (!root) {
this.notifyPath(parts.join('.'), value);
}
} else {
prop[path] = value;
}
},
/**
* Convienence method for reading a value from a path.
*
* Note, if any part in the path is undefined, this method returns
* `undefined` (this method does not throw when dereferencing undefined
* paths).
*
* @method get
* @param {(string|Array<(string|number)>)} path Path to the value
* to read. The path may be specified as a string (e.g. `foo.bar.baz`)
* or an array of path parts (e.g. `['foo.bar', 'baz']`). Note that
* bracketed expressions are not supported; string-based path parts
* *must* be separated by dots. Note that when dereferencing array
* indicies, the index may be used as a dotted part directly
* (e.g. `users.12.name` or `['users', 12, 'name']`).
* @param {Object=} root Root object from which the path is evaluated.
* @return {*} Value at the path, or `undefined` if any part of the path
* is undefined.
*/
get: function(path, root) {
var prop = root || this;
var parts = this._getPathParts(path);
var last = parts.pop();
while (parts.length) {
prop = prop[parts.shift()];
if (!prop) {
return;
}
}
return prop[last];
},
_pathEffector: function(path, value) {
// get root property
var model = this._modelForPath(path);
// search property effects of the root property for 'annotation' effects
var fx$ = this._propertyEffects[model];
if (fx$) {
fx$.forEach(function(fx) {
var fxFn = this['_' + fx.kind + 'PathEffect'];
if (fxFn) {
fxFn.call(this, path, value, fx.effect);
}
}, this);
}
// notify runtime-bound paths
if (this._boundPaths) {
this._notifyBoundPaths(path, value);
}
},
_annotationPathEffect: function(path, value, effect) {
if (effect.value === path || effect.value.indexOf(path + '.') === 0) {
// TODO(sorvell): ideally the effect function is on this prototype
// so we don't have to call it like this.
Polymer.Bind._annotationEffect.call(this, path, value, effect);
} else if ((path.indexOf(effect.value + '.') === 0) && !effect.negate) {
// locate the bound node
var node = this._nodes[effect.index];
if (node && node.notifyPath) {
var p = this._fixPath(effect.name , effect.value, path);
node.notifyPath(p, value, true);
}
}
},
_complexObserverPathEffect: function(path, value, effect) {
if (this._pathMatchesEffect(path, effect)) {
Polymer.Bind._complexObserverEffect.call(this, path, value, effect);
}
},
_computePathEffect: function(path, value, effect) {
if (this._pathMatchesEffect(path, effect)) {
Polymer.Bind._computeEffect.call(this, path, value, effect);
}
},
_annotatedComputationPathEffect: function(path, value, effect) {
if (this._pathMatchesEffect(path, effect)) {
Polymer.Bind._annotatedComputationEffect.call(this, path, value, effect);
}
},
_pathMatchesEffect: function(path, effect) {
var effectArg = effect.trigger.name;
return (effectArg == path) ||
(effectArg.indexOf(path + '.') === 0) ||
(effect.trigger.wildcard && path.indexOf(effectArg) === 0);
},
/**
* Aliases one data path as another, such that path notifications from one
* are routed to the other.
*
* @method linkPaths
* @param {string} to Target path to link.
* @param {string} from Source path to link.
*/
linkPaths: function(to, from) {
this._boundPaths = this._boundPaths || {};
if (from) {
this._boundPaths[to] = from;
// this.set(to, this.get(from));
} else {
this.unlinkPaths(to);
// this.set(to, from);
}
},
/**
* Removes a data path alias previously established with `linkPaths`.
*
* Note, the path to unlink should be the target (`to`) used when
* linking the paths.
*
* @method unlinkPaths
* @param {string} path Target path to unlink.
*/
unlinkPaths: function(path) {
if (this._boundPaths) {
delete this._boundPaths[path];
}
},
_notifyBoundPaths: function(path, value) {
var from, to;
for (var a in this._boundPaths) {
var b = this._boundPaths[a];
if (path.indexOf(a + '.') == 0) {
this.notifyPath(this._fixPath(b, a, path), value);
} else if (path.indexOf(b + '.') == 0) {
this.notifyPath(this._fixPath(a, b, path), value);
}
}
},
_fixPath: function(property, root, path) {
return property + path.slice(root.length);
},
_notifyPath: function(path, value) {
var rootName = this._modelForPath(path);
var dashCaseName = Polymer.CaseMap.camelToDashCase(rootName);
var eventName = dashCaseName + this._EVENT_CHANGED;
this.fire(eventName, {
path: path,
value: value
}, {bubbles: false});
},
_modelForPath: function(path) {
var dot = path.indexOf('.');
return (dot < 0) ? path : path.slice(0, dot);
},
_EVENT_CHANGED: '-changed',
_notifySplice: function(array, path, index, added, removed) {
var splices = [{
index: index,
addedCount: added,
removed: removed,
object: array,
type: 'splice'
}];
var change = {
keySplices: Polymer.Collection.applySplices(array, splices),
indexSplices: splices
};
this.set(path + '.splices', change);
if (added != removed.length) {
this.notifyPath(path + '.length', array.length);
}
// Null here to allow potentially large splice records to be GC'ed
change.keySplices = null;
change.indexSplices = null;
},
/**
* Adds items onto the end of the array at the path specified.
*
* The arguments after `path` and return value match that of
* `Array.prototype.push`.
*
* This method notifies other paths to the same array that a
* splice occurred to the array.
*
* @method push
* @param {String} path Path to array.
* @param {...any} var_args Items to push onto array
* @return {number} New length of the array.
*/
push: function(path) {
var array = this.get(path);
var args = Array.prototype.slice.call(arguments, 1);
var len = array.length;
var ret = array.push.apply(array, args);
if (args.length) {
this._notifySplice(array, path, len, args.length, []);
}
return ret;
},
/**
* Removes an item from the end of array at the path specified.
*
* The arguments after `path` and return value match that of
* `Array.prototype.pop`.
*
* This method notifies other paths to the same array that a
* splice occurred to the array.
*
* @method pop
* @param {String} path Path to array.
* @return {any} Item that was removed.
*/
pop: function(path) {
var array = this.get(path);
var hadLength = Boolean(array.length);
var args = Array.prototype.slice.call(arguments, 1);
var ret = array.pop.apply(array, args);
if (hadLength) {
this._notifySplice(array, path, array.length, 0, [ret]);
}
return ret;
},
/**
* Starting from the start index specified, removes 0 or more items
* from the array and inserts 0 or more new itms in their place.
*
* The arguments after `path` and return value match that of
* `Array.prototype.splice`.
*
* This method notifies other paths to the same array that a
* splice occurred to the array.
*
* @method splice
* @param {String} path Path to array.
* @param {number} start Index from which to start removing/inserting.
* @param {number} deleteCount Number of items to remove.
* @param {...any} var_args Items to insert into array.
* @return {Array} Array of removed items.
*/
splice: function(path, start, deleteCount) {
var array = this.get(path);
// Normalize fancy native splice handling of crazy start values
if (start < 0) {
start = array.length - Math.floor(-start);
} else {
start = Math.floor(start);
}
if (!start) {
start = 0;
}
var args = Array.prototype.slice.call(arguments, 1);
var ret = array.splice.apply(array, args);
var addedCount = Math.max(args.length - 2, 0);
if (addedCount || ret.length) {
this._notifySplice(array, path, start, addedCount, ret);
}
return ret;
},
/**
* Removes an item from the beginning of array at the path specified.
*
* The arguments after `path` and return value match that of
* `Array.prototype.pop`.
*
* This method notifies other paths to the same array that a
* splice occurred to the array.
*
* @method shift
* @param {String} path Path to array.
* @return {any} Item that was removed.
*/
shift: function(path) {
var array = this.get(path);
var hadLength = Boolean(array.length);
var args = Array.prototype.slice.call(arguments, 1);
var ret = array.shift.apply(array, args);
if (hadLength) {
this._notifySplice(array, path, 0, 0, [ret]);
}
return ret;
},
/**
* Adds items onto the beginning of the array at the path specified.
*
* The arguments after `path` and return value match that of
* `Array.prototype.push`.
*
* This method notifies other paths to the same array that a
* splice occurred to the array.
*
* @method unshift
* @param {String} path Path to array.
* @param {...any} var_args Items to insert info array
* @return {number} New length of the array.
*/
unshift: function(path) {
var array = this.get(path);
var args = Array.prototype.slice.call(arguments, 1);
var ret = array.unshift.apply(array, args);
if (args.length) {
this._notifySplice(array, path, 0, args.length, []);
}
return ret;
}
});
})();
</script>