-
Notifications
You must be signed in to change notification settings - Fork 7
/
Variable.js
3224 lines (3123 loc) · 97.6 KB
/
Variable.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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (root, factory) { if (typeof define === 'function' && define.amd) {
define(['./util/lang'], factory) } else if (typeof module === 'object' && module.exports) {
module.exports = factory(require('./util/lang')) // Node
}}(this, function (lang) {
var deny = {}
var noChange = {}
var context
var WeakMap = lang.WeakMap
var Map = lang.Map
var Set = lang.Set
var setPrototypeOf = lang.setPrototypeOf
var getPrototypeOf = Object.getPrototypeOf || (function(base) { return base.__proto__ })
var isGenerator = lang.isGenerator
var undefined // makes it faster to be locally scoped
// update types
var RequestChange = 3
var RequestSet = 4
var NOT_MODIFIED = {
name: 'Not modified',
toString: function () {
return 'Marker for not-modified response'
},
}
var GET_TYPED_ARRAY = {
getTyped: true
}
var GET_TYPED_OR_UNTYPED_ARRAY = {
getTyped: true,
allowUntyped: true
}
var GET_VALID_TYPE = {
ensureValidType: true
}
var propertyListenersMap = new lang.WeakMap(null, 'propertyListenersMap')
var isStructureChecked = new lang.WeakMap()
var nextVersion = Date.now()
var CacheEntry = lang.compose(WeakMap, function() {
},{
_propertyChange: function(propertyName) {
this.variable._propertyChange(propertyName, contextFromCache(this))
}
})
var listenerId = 1
function when(value, callback, errback) {
if (value && value.then) {
return value.then(callback, errback)
}
return callback(value)
}
function whenStrict(value, callback) {
if (value && value.then && !value.notifies) {
return value.then(callback)
}
return callback(value)
}
function Context(subject, notifies){
this.subject = subject
if (notifies) {
this.notifies = notifies
}
}
Context.prototype = {
constructor: Context,
newContext: function(variable) {
return new this.constructor(this.subject, this.notifies)
},
executeWithin: function(executor) {
var previousContext = context
try {
context = this
return executor()
} finally {
context = previousContext
}
},
//version: 2166136261, // FNV-1a prime seed
version: 1,
restart: function() {
//this.version = 2166136261
},
contextualize: function(variable, parentContext) {
// resolve the contextualization of a variable, and updates this context to be aware of what distinctive aspect of the context has
// been used for resolution
var contextualized
if (this.distinctSubject) {
var contextMap = variable._contextMap || (variable._contextMap = new lang.WeakMap())
contextualized = contextMap.get(this.distinctSubject)
if (!contextualized) {
contextMap.set(this.distinctSubject, contextualized = Object.create(variable))
contextualized.listeners = false
contextualized.context = this
var sources = this.sources
for (var i = 0, l = sources.length; i < l; i++) {
contextualized[sources[i]] = sources[++i]
}
}
this.contextualized = contextualized
// do the merge
if (parentContext) {
parentContext.merge(this)
}
} else {
contextualized = variable
}
//if (this.contextualized && this.contextualized !== contextualized) {
// TOOD: if it has previously been contextualized to a different context (can happen in a promise/async situation), stop previous notifiers and start new ones
//}
return contextualized
},
setVersion: function(version) {
/* // FNV1a hash algorithm 32-bit
return this.version = (this.version ^ (version || 0)) * 16777619 >>> 0*/
/* // 54 bit FNV1a hash algorithm
var xored = this.version ^ (version || 0)
// 435 + 1099511627776 = 1099511628211 is 64 bit FNV prime
return this.version =
xored * 435 + // compute hash on lower 32 bits
(xor & 16777215) * 1099511627776 + // compute hash on lower 24 bits that overflow into upper 32 bits
((this.version / 4294967296 >>> 0) * 435 & 2097151) * 4294967296 // hash on upper 32 bits*/
// 54 bit derivative of FNV1a that better uses JS numbers/operators
// a fast, efficient hash
//return this.version = (this.version ^ (version || 0)) * 1049011 + (this.version / 5555555 >>> 0)
// if we are using globally monotonically increasing version, we can just use max
if (isNaN(version)) {
throw new Error('Bad version')
}
return this.version = Math.max(this.version, version)
},
merge: function(childContext) {
if (!this.distinctSubject) {
this.distinctSubject = childContext.distinctSubject
}
},
specify: function(Variable) {
// specify a particular instance of a generic variable
var subject = this.subject
var subjectMap = subject.constructor.ownedClasses
var specifiedInstance
if (subjectMap) {
if (!this.distinctSubject) {
this.distinctSubject = subject
}
var instanceMap = subjectMap.get(Variable)
if (instanceMap) {
specifiedInstance = instanceMap.get(subject)
if (!specifiedInstance) {
instanceMap.set(subject, specifiedInstance = instanceMap.createInstance ? instanceMap.createInstance(subject) : new Variable())
}
return specifiedInstance
}
}
// else if no specific context is found, return default instance
return Variable.defaultInstance
},
getContextualized: function(variable) {
if (!this.subject) {
// no subject, just use the default variable
return variable
}
// returns a variable that has already been contextualized
var instance = variable._contextMap && this.subject && variable._contextMap.get(this.subject)
if (instance && instance.context && instance.context.matches(this)) {
return instance
}
},
matches: function(context) {
// does another context match the resolution of this one?
return context.subject === this.subject
}
}
function NotifyingContext(listener, subject){
this.subject = subject
this.listener = listener
}
NotifyingContext.prototype = Object.create(Context.prototype)
NotifyingContext.prototype.constructor = NotifyingContext
function registerListener(value, listener) {
var listeners = propertyListenersMap.get(value)
var id = listener.listenerId || (listener.listenerId = ('-' + listenerId++))
if (listeners) {
if (listeners[id] === undefined) {
listeners[id] = listeners.push(listener) - 1
}
}else{
propertyListenersMap.set(value, listeners = [listener])
listeners[id] = 0
if (Variable.autoObserveObjects) {
observe(value)
}
}
listener.listeningToObject = value
}
function deregisterListener(listener) {
if (listener.listeningToObject) {
var value = listener.listeningToObject
listener.listeningToObject = null
var listeners = propertyListenersMap.get(value)
if (listeners) {
var index = listeners[listener.listenerId]
if (index > -1) {
listeners.splice(index, 1)
delete listeners[listener.listenerId]
}
}
}
}
function UpdateEvent() {
this.visited = new Set()
}
UpdateEvent.prototype.type = 'replaced'
function ReplacedEvent(triggerEvent) {
this.visited = triggerEvent ? triggerEvent.visited : new Set()
}
ReplacedEvent.prototype.type = 'replaced'
function PropertyChangeEvent(key, propertyEvent, parent) {
this.key = key
this.propertyEvent = propertyEvent
this.parent = parent
this.visited = propertyEvent.visited
}
PropertyChangeEvent.prototype.type = 'property'
PropertyChangeEvent.prototype.getVersion = function() {
return this.propertyEvent.getVersion ? this.propertyEvent.getVersion() : this.parent.version
}
function SplicedEvent(modifier, items, removed, start, deleteCount) {
this.visited = new Set()
this.modifier = modifier
this.items = items
this.removed = removed
this.start = start
this.deleteCount = deleteCount
}
SplicedEvent.prototype.type = 'spliced'
function EntryEvent(key, value, entryEvent) {
this.entryEvent = entryEvent
this.visited = entryEvent.visited
this.key = key
this.value = value
}
EntryEvent.prototype.type = 'entry'
EntryEvent.prototype.doesAffect = function(subject) {
return this.value.constructor.for(subject).id.valueOf() == this.value.id.valueOf()
}
function DeletedEvent(key, value) {
this.key = key
this.value = value
this.visited = new Set()
}
DeletedEvent.prototype.type = 'deleted'
function AddedEvent(key, value) {
this.key = key
this.value = value
this.visited = new Set()
}
AddedEvent.prototype.type = 'added'
AddedEvent.prototype.doesAffect = function() {
return false
}
function forPropertyNotifyingValues(variable, properties, callback) {
if (variable === properties) {
forPropertyNotifyingValues(variable, variable._properties, callback)
}
for (var key in properties) {
var property = properties[key]
if (property && property.parent == variable) {
if (property.returnedVariable) {
callback(property.returnedVariable)
}
if (property.hasChildNotifiers) {
var subProperties = property._properties
if (subProperties) {
forPropertyNotifyingValues(property, property, callback)
}
}
}
}
}
function assignPromise(variable, promise, callback) {
var isSync
promise.then(function(value) {
if (isSync !== false) {
// synchronous resolution
isSync = true
} else if (variable.promise === promise) {
// async resolution make sure we are the still the most recent promise
variable.promise = null
} else {
// if async and we are not the most recent, just return
return
}
if (callback) { // custom handler
callback(value)
} else {
variable.value = value
}
}, function(error) {
if (isSync !== false) {
// synchronous resolution
isSync = true
} else if (variable.promise === promise) {
// async resolution make sure we are the still the most recent promise
variable.promise = null
} else {
// if async and we are not the most recent, just return
return
}
variable.error = error
})
if (!isSync) {
isSync = false
variable.promise = promise
}
return promise
}
function Variable(value) {
if (this instanceof Variable) {
// new call, may eventually use new.target
if (value !== undefined) {
if (value && value.then && !value.notifies) {
assignPromise(this, value)
} else {
this.value = value
}
}
} else {
return Variable.with(value)
}
}
Variable._logStackTrace = function(v) {
var stack = (new Error().stack || '').split(/[\r\n]+/)
if (stack[0] && /^Error\s*/.test(stack[0])) stack.shift()
if (stack[0] && /_logStackTrace/.test(stack[0])) stack.shift()
var coalesce = (this._debugOpts && this._debugOpts.coalesce) || []
if (this._debugOpts && this._debugOpts.shortStackTrace) {
// find the first non-coalesced line
var line
stack.some(function(line) {
if (!coalesce.some(function(re) {
return re.re.test(line)
})) {
line = stack[0]
}
})
console.log('Variable ' + v.__debug + ' changed', line && line.replace(/^\s+/, ''))
} else {
if (coalesce.length) {
var s = []
var re
for (var i = 0; i < stack.length; i++) {
var line = stack[i]
if (re) {
if (re.test(line)) continue
re = null
}
re
coalesce.some(function(re) {
return re = re.re.test(line)
})
line = line.replace(/^\s+/,'')
if (re) {
s.push('(' + re.name + ') ' + line)
re = re.re
} else {
s.push(line)
}
}
stack = s
}
var stackObject = this._debugOpts && this._debugOpts.stackObject
if (stackObject) {
console.log('Variable ' + v.__debug + ' changed', stack)
} else {
console.log('Variable ' + v.__debug + ' changed\r\n' + stack.join('\r\n'))
}
}
}
Variable._debugOpts = {
coalesce: [{ name: 'alkali', re: /\/alkali\// }, { name: 'Promise', re: /(Promise\.)|(PromiseArray\.)|(\/bluebird\/)/ }],
stackObject: false
}
var VariablePrototype = Variable.prototype = {
// for debugging use
constructor: Variable,
valueOf: function(allowPromise) {
var result = this.gotValue(this.getValue())
return (allowPromise || !(result && result.then)) ? result : undefined
},
then: function(onFulfilled, onRejected) {
var result, isAsyncPromise
try {
result = this.valueOf(true)
isAsyncPromise = result && result.then
if (!isAsyncPromise) {
result = new lang.SyncPromise(result) // ensure it is promise-like
}
} catch (error) {
result = new lang.SyncErrorPromise(error)
}
if (onFulfilled || onRejected) { // call then if we have any callbacks
if (isAsyncPromise && context) {
// if it is async and we have a context, we will restore it for the callback
var currentContext = context
return result.then(onFulfilled && function(result) {
return currentContext.executeWithin(function() {
return onFulfilled(result)
})
}, onRejected && function(error) {
return currentContext.executeWithin(function() {
return onRejected(error)
})
})
}
return result.then(onFulfilled, onRejected)
}
return result
},
getValue: function(forChild) {
if (context) {
context.setVersion(forChild ? this.version : Math.max(this.version || 0, this.versionWithChildren || 0))
}
var key = this.key
var parent
if (key !== undefined && (parent = this.parent) != null) {
if (context) {
if (context.ifModifiedSince != null) {
// just too complicated to handle NOT_MODIFED objects for now
// TODO: Maybe handle this and delegate NOT_MODIFIED through this
// chain and through gotValue
context.ifModifiedSince = undefined
}
}
var property = this
var object
if (parent.getValue) {
// parent needs value context, might want to do separate context,
// but would need to treat special so it retrieves the version
// only and not the versionWithChildren
object = parent.getValue(true)
} else {
object = parent.value
}
if (object && object.then && !object.notifies) {
return when(object, function(object) {
var value = object == null ? undefined :
typeof object.property === 'function' ? object.property(key) :
typeof object.get === 'function' ? object.get(key) : object[key]
//if (property.listeners) {
var listeners = propertyListenersMap.get(object)
if (listeners && listeners.observer && listeners.observer.addKey) {
listeners.observer.addKey(key)
}
//}
return value
})
}
var value = object == null ? undefined :
typeof object.property === 'function' ? object.property(key) :
typeof object.get === 'function' ? object.get(key) : object[key]
//if (property.listeners) {
var listeners = propertyListenersMap.get(object)
if (listeners && listeners.observer && listeners.observer.addKey) {
listeners.observer.addKey(key)
}
//}
return value !== undefined ?
value : this.default
}
if (this.promise) {
return this.promise
}
var value = this.value
return value !== undefined ?
value : this.default
},
gotValue: function(value) {
var previousNotifyingValue = this.returnedVariable
var variable = this
if (previousNotifyingValue) {
if (value === previousNotifyingValue) {
// nothing changed, immediately return valueOf
if (context && context.ifModifiedSince > 0) // we don't want the nested value to return a NOT_MODIFIED
context.ifModifiedSince = undefined
return value.valueOf(true)
}
// if there was a another value that we were dependent on before, stop listening to it
// TODO: we may want to consider doing cleanup after the next rendering turn
if (variable.listeners) {
previousNotifyingValue.stopNotifies(variable)
}
variable.returnedVariable = null
}
if (value && value.notifies) {
variable.returnedVariable = value
if (variable.listeners) {
value.notifies(variable)
}
if (context && context.ifModifiedSince > 0) // we don't want the nested value to return a NOT_MODIFIED
context.ifModifiedSince = undefined
value = value.valueOf(true)
}
if (value && value.then) {
var deferredContext = context
return value.then(function(value) {
if (value) {
if (value.__variable) {
value = value.__variable
}
if (value.subscribe) {
if (deferredContext) {
return deferredContext.executeWithin(function() {
return Variable.prototype.gotValue.call(variable, value)
})
} else {
return Variable.prototype.gotValue.call(variable, value)
}
}
}
return value
})
}
return value
},
PropertyClass: Variable,
property: function(key, PropertyClass) {
var propertyVariable = this[key]
if (!propertyVariable || !propertyVariable.notifies) {
propertyVariable = this._properties && this._properties[key]
}
if (!propertyVariable) {
// create the property variable
var Class = PropertyClass
if (!Class) {
Class = this.constructor[key]
if (typeof Class !== 'function' || !Class.isPropertyClass) {
Class = this.PropertyClass
}
}
propertyVariable = new Class()
propertyVariable.key = key
propertyVariable.parent = this
if (this[key] === undefined) {
this[key] = propertyVariable
} else {
(this._properties || (this._properties = {}))[key] = propertyVariable
}
} else if (PropertyClass) {
if (!(propertyVariable instanceof PropertyClass)) {
throw new TypeError('Existing property variable does not match requested variable type')
}
}
return propertyVariable
},
for: function(subject) {
if (subject && subject.target && !subject.constructor.getForClass) {
// makes HTML events work
subject = subject.target
}
if (this.parent) {
return this.parent.for(subject).property(this.key)
}
return new ContextualizedVariable(this, subject || defaultContext)
},
get isWritable() {
return this.fixed ? !this.value || this.value.isWritable : this._isWritable
},
set isWritable(isWritable) {
this._isWritable = isWritable
},
_isWritable: true,
_propertyChange: function(propertyName, object, type) {
if (this.onPropertyChange) {
this.onPropertyChange(propertyName, object)
}
this.updated(new PropertyChangeEvent(propertyName, new ReplacedEvent(), this))
},
eachKey: function(callback) {
for (var i in this._properties) {
callback(i)
}
for (var i in this) {
if (this.hasOwnProperty[i]) {
var value = this[i]
if (value && value.parent == this && value.listeners) {
callback(i)
}
}
}
},
apply: function(instance, args) {
return new Transform(args[0], this, args)
},
call: function(instance) {
return this.apply(instance, Array.prototype.slice.call(arguments, 1))
},
forDependencies: function(callback) {
if (this.returnedVariable) {
callback(this.returnedVariable)
}
if (this.hasNotifyingChild) {
forPropertyNotifyingValues(this, this, callback)
}
if (this.parent) {
callback(this.parent)
}
},
init: function() {
var variable = this
var contextualizes, sources = [] // TODO: optimize this
this.forDependencies(function(dependency) {
var contextualized = dependency.notifies(variable)
if (contextualized !== dependency) {
contextualizes = true
}
sources.push(contextualized)
})
/* if (contextualizes) {
var contextualized = new ContextualizedVariable()
//context.instanceMap.set(this, contextualized)
contextualized.sources = sources
contextualized.init()
return contextualized
}
*/
if (this.listeningToObject === null) {
// we were previously listening to an object, but it needs to be restored
// calling valueOf will cause the listening object to be restored
this.valueOf()
}
return this
},
cleanup: function() {
this.listeners = false
var handles = this.handles
if (handles) {
for (var i = 0; i < handles.length; i++) {
handles[i].remove()
}
}
this.handles = null
var returnedVariable = this.returnedVariable
var variable = this
this.forDependencies(function(dependency) {
dependency.stopNotifies(variable)
})
},
version: 0,
versionWithChildren: 0,
updateVersion: function(version) {
var dateBasedVersion = Date.now()
if (dateBasedVersion > nextVersion) {
nextVersion = dateBasedVersion
}
this.version = nextVersion++
},
getVersion: function() {
return Math.max(this.version,
this.returnedVariable && this.returnedVariable.getVersion ? this.returnedVariable.getFullVersion(context) : 0,
this.parent ? this.parent.getVersion(context) : 0)
},
getFullVersion: function() {
return Math.max(this.versionWithChildren, this.getVersion())
},
getSubject: function(selectVariable) {
return this.subject
},
getUpdates: function(since) {
var updates = []
var nextUpdateMap = this.nextUpdateMap
if (nextUpdateMap && since) {
while ((since = nextUpdateMap.get(since))) {
if (since.type === 'replaced') {
// if it was refresh, we can clear any prior entries
updates = []
}
updates.push(since)
}
}
return updates
},
_initUpdate: function(updateEvent, isDownstream) {
if (!updateEvent.version) {
var dateBasedVersion = Date.now()
if (dateBasedVersion > nextVersion) {
nextVersion = dateBasedVersion
}
updateEvent.version = nextVersion++
}
if (updateEvent instanceof PropertyChangeEvent) {
this.versionWithChildren = updateEvent.version
} else if (!isDownstream) {
this.version = updateEvent.version
}
return updateEvent
},
updated: function(updateEvent, by, isDownstream) {
if (!updateEvent) {
updateEvent = new ReplacedEvent()
updateEvent.source = this
}
if (updateEvent.visited.has(this)){
// if this event has already visited this variable, skip it
return updateEvent
}
updateEvent.visited.add(this)
if (this.__debug) {
// debug is on
Variable._logStackTrace(this)
}
/*var contextualInstance = context && context.getContextualized(this)
if (contextualInstance) {
contextualInstance.updated(updateEvent, this)
}
// at some point we could do an update list so that we could incrementally update
// lists in non-live situations
if (this.lastUpdate) {
var nextUpdateMap = this.nextUpdateMap
if (!nextUpdateMap) {
nextUpdateMap = this.nextUpdateMap = new lang.WeakMap()
}
nextUpdateMap.set(this.lastUpdate, updateEvent)
}
this.lastUpdate = updateEvent */
this._initUpdate(updateEvent, isDownstream)
var listeners = this.listeners
if (listeners) {
var variable = this
// make a copy, in case they change
listeners = listeners.slice()
for (var i = 0, l = listeners.length; i < l; i++) {
var dependent = listeners[i]
if (dependent.parent && !(updateEvent instanceof ReplacedEvent)) {
if (updateEvent instanceof PropertyChangeEvent) {
if (dependent.key === updateEvent.key) {
dependent.updated(updateEvent.propertyEvent, variable)
}
} else {
var childEvent = new ReplacedEvent(updateEvent)
dependent.updated(childEvent, variable, true)
}
} else {
dependent.updated(updateEvent, variable, true)
}
}
}
if (updateEvent instanceof PropertyChangeEvent || updateEvent instanceof ReplacedEvent) {
if (this.returnedVariable && this.fixed) {
this.returnedVariable.updated(updateEvent, this)
}
var Class = this.constructor
var variable = this
if (Class.collection) {
Class.collection.updated(new EntryEvent(this.id, this, updateEvent))
}
}
if (this.parent) {
this.parent.updated(new PropertyChangeEvent(this.key, updateEvent, this.parent), this)
}
if (this.collection) {
this.collection.updated(updateEvent, this)
}
return updateEvent
},
invalidate: function() {
// for back-compatibility for now
this.updated()
},
notifies: function(target) {
// TODO: Eventually we want this to be trigerred from context, but context gets shared with returned variables, so will need to handle that
if (!target) {
throw new Error('No listener provided for notification')
}
var listeners = this.listeners
if (!listeners || !this.hasOwnProperty('listeners')) {
var variable = this.init()
variable.listeners = listeners = [target]
return variable
} else if (listeners.indexOf(target) === -1) {
listeners.push(target)
}
return this
},
subscribe: function(listener) {
// ES7 Observable (and baconjs) compatible API
var updated
var updateQueued
var variable = this
// it is important to make sure you register for notifications before getting the value
if (typeof listener === 'function') {
// BaconJS compatible API
var variable = this
var event = {
value: function() {
return new Context(null, true).executeWithin(function() {
return variable.valueOf(true)
})
}
}
updated = function() {
updateQueued = false
listener(event)
}
} else if (listener.next) {
// Assuming ES7 Observable API. It is actually a streaming API, this pretty much violates all principles of reactivity, but we will support it
updated = function() {
updateQueued = false
variable.then(function(value) {
listener.next(value)
}, function(error) {
listener.error(value)
})
}
} else {
throw new Error('Subscribing to an invalid listener, the listener must be a function, or have an update or next method')
}
var updateReceiver = {
updated: function() {
if (updateQueued) {
return
}
updateQueued = true
lang.nextTurn(updated)
}
}
updated()
this.notifies(updateReceiver)
return {
unsubscribe: function() {
variable.stopNotifies(updateReceiver)
}
}
},
stopNotifies: function(dependent) {
var listeners = this.listeners
if (listeners) {
var index = listeners.indexOf(dependent)
if (index > -1) {
listeners.splice(index, 1)
if (listeners.length === 0) {
// clear the listeners so it will be reinitialized if it has
// listeners again
this.cleanup()
}
}
}
},
put: function(value, event) {
if (this.parent && this.key !== undefined) {
return changeValue(this, RequestChange, value, event)
}
var oldValue = this.getValue ? this.getValue() : this.value
if (oldValue === value && typeof value != 'object') {
return noChange
}
if (oldValue && oldValue.put && oldValue.notifies) {
// if it is set to fixed, we see we can put in the current variable
if (this.fixed || !(value && value.put && value.notifies)) {
try {
return oldValue.put(value)
} catch (error) {
if (!error.deniedPut) {
throw error
}// else if the put was denied, continue on and set the value on this variable
}
}
}
if (this.promise)
this.promise = null
if (value && value.then && !value.notifies) {
value = assignPromise(this, value)
} else {
this.value = value
if (value && value.put) {
// preserve a reference to the original variable so we can `save()` back into it
this.copiedFrom = value
}
}
event = event || new ReplacedEvent()
event.oldValue = oldValue
event.target = this
this.updated(event, this)
return value
},
get: function(key) {
if (this[key] || (this._properties && this._properties[key])) {
return this.property(key).valueOf(true)
}
var object = this.getValue()
if (!object) {
return
}
if (typeof object.get === 'function') {
return object.get(key)
}
var value = object[key]
if (value && value.notifies) {
// nested variable situation, get underlying value
return value.valueOf(true)
}
return value
},
set: function(key, value, event) {
// TODO: create an optimized route when the property doesn't exist yet
changeValue(this.property(key), RequestSet, value, event)
},
undefine: function(key) {
this.set(key, undefined)
},
is: function(newValue, event) {
if (this.parent) {
var parent = this.parent
var key = this.key
var object = (parent.getValue ? parent.getValue(true) : parent.value)
var parentEvent = new PropertyChangeEvent(key, event || new ReplacedEvent(), parent)
if (object) {
object[key] = newValue
this.updated(parentEvent, this)
} else {
object = (typeof key === 'number' ? [] : {})
object[key] = newValue
parent.is(object, parentEvent)
}
return this
}
this.fixed = true
this.returnedVariable = null
if (this.promise)
this.promise = null
if (newValue && newValue.then && !newValue.notifies) {
assignPromise(this, newValue)
} else
this.value = newValue
this.updated(new ReplacedEvent(), this)
return this
},
proxy: function(proxiedVariable) {
return this.is(proxiedVariable)
},
next: function(value) {
// for ES7 observable compatibility
this.put(value)
},
error: function(error) {
// for ES7 observable compatibility
var listeners = this.listeners
if (listeners) {
// make a copy, in case they change
listeners.forEach(function(dependent) {
// skip notifying property listeners if we are headed up the parent chain
dependent.error(error)
})
}
},
complete: function(value) {
// for ES7 observable compatibility
this.put(value)
},
save: function() {
if (this.copiedFrom) {
this.copiedFrom.put(this.valueOf())
return true
} else {
return false
}
},
onValue: function(listener) {
return this.subscribe(function(event) {
when(event.value(), function(value) {
listener(value)