-
Notifications
You must be signed in to change notification settings - Fork 130
/
jquery.observable.js
1363 lines (1252 loc) · 48.2 KB
/
jquery.observable.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
/*! JsObservable v1.0.15: http://jsviews.com/#jsobservable */
/*
* Subcomponent of JsViews
* Data change events for data-linking
*
* Copyright 2024, Boris Moore
* Released under the MIT License.
*/
//jshint -W018, -W041, -W120
(function(factory, global) {
// global var is the this object, which is window when running in the usual browser environment
var $ = global.jQuery;
if (typeof exports === "object") { // CommonJS e.g. Browserify
module.exports = $
? factory(global, $)
: function($) { // If no global jQuery, take jQuery passed as parameter: require("jsobservable")(jQuery)
return factory(global, $);
};
} else if (typeof define === "function" && define.amd) { // AMD script loader, e.g. RequireJS
define(["jquery"], function($) {
return factory(global, $); // Require jQuery
});
} else { // Browser using plain <script> tag
factory(global, false);
}
} (
// factory (for jsviews.js)
function(global, $) {
"use strict";
//========================== Top-level vars ==========================
// global var is the this object, which is window when running in the usual browser environment
var setGlobals = $ === false; // Only set globals if script block in browser (not AMD and not CommonJS)
$ = $ || global.jQuery;
if (!$ || !$.fn) {
// jQuery is not loaded.
throw "jquery.observable.js requires jQuery"; // We require jQuery
}
var versionNumber = "v1.0.15",
_ocp = "_ocp", // Observable contextual parameter
$observe, $observable,
$views = $.views =
$.views ||
setGlobals && global.jsrender && jsrender.views || //jsrender was loaded before jquery.observable
{ // jsrender not loaded so set up $.views and $.views.sub here, and merge back in jsrender if loaded afterwards
jsviews: versionNumber,
sub: { // subscription, e.g. JsViews integration
settings: {}
},
settings: {
advanced: function(value) {
$subSettingsAdvanced = $subSettings.advanced = $subSettings.advanced || {_jsv: true};
return value
? (
"_jsv" in value && ($subSettingsAdvanced._jsv = value._jsv),
$sub.advSet(),
$views.settings
)
: $subSettingsAdvanced;
}
}
},
$sub = $views.sub,
$subSettings = $sub.settings,
$subSettingsAdvanced = $subSettings.advanced,
$isFunction = $.isFunction,
$expando = $.expando,
$isArray = $.isArray,
STRING = "string",
OBJECT = "object";
if ($views.jsviews !== versionNumber) {
// Different version of jsRender was loaded
throw "jquery.observable.js requires jsrender.js " + versionNumber;
}
if (!$.observe) {
var $eventSpecial = $.event.special,
slice = [].slice,
splice = [].splice,
concat = [].concat,
PARSEINT = parseInt,
rNotWhite = /\S+/g,
rShallowPath = /^[^.[]*$/, // No '.' or '[' in path
propertyChangeStr = $sub.propChng = $sub.propChng || "propertyChange",// These two settings can be overridden on settings after loading
arrayChangeStr = $sub.arrChng = $sub.arrChng || "arrayChange", // jsRender, and prior to loading jquery.observable.js and/or JsViews
cbBindingsStore = {},
observeStr = propertyChangeStr + ".observe",
observeObjKey = 1,
observeCbKey = 1,
observeInnerCbKey = 1,
$data = $.data,
remove = {}, // flag for removeProperty
asyncBatch = [],
//========================== Top-level functions ==========================
getCbKey = function(cb) {
return cb
? (cb._cId = cb._cId || (".obs" + observeCbKey++))
: "";
},
ObjectObservable = function(ns, data) {
this._data = data;
this._ns = ns;
return this;
},
ArrayObservable = function(ns, data) {
this._data = data;
this._ns = ns;
return this;
},
wrapArray = function(data) {
return $isArray(data)
? [data]
: data;
},
dependsPaths = function(paths, root, callback) {
// Process depends = ... paths to resolve objects, and recursively process functions.
paths = paths
? $isArray(paths)
? paths
: [paths]
: [];
var i, path, object, rt,
nextObj = object = root,
l = paths && paths.length,
out = [];
for (i = 0; i < l; i++) {
path = paths[i];
if ($isFunction(path)) { // path is a depends function, returning [path1, ...]
rt = root.tagName
? root.linkCtx.data // root is tag instance. rt is current data context of tag
: root; // rt = root = current data context of computed prop
out = out.concat(dependsPaths(path.call(root, rt, callback), rt, callback));
continue;
} else if (typeof path !== STRING) {
root = nextObj = path = (path === undefined ? null : path);
if (nextObj !== object) {
out.push(object = nextObj);
}
continue;
}
if (nextObj !== object) {
out.push(object = nextObj);
}
out.push(path);
}
if (out.length) {
// Switch on allowArray, for depends paths, by passing {_ar: ...} objects to switch on allowArray then return to contextual allowArray value
out.unshift({_ar: 1});
out.push({_ar: -1});
}
return out;
},
onDataChange = function(ev, eventArgs) {
function isOb(val) {
return typeof val === OBJECT && (paths[0] || !noArray && $isArray(val));
}
if (!(ev.data && ev.data.off)) {
// Skip if !!ev.data.off: - a handler that has already been removed (maybe was on handler collection at call time - then removed by another handler)
var allPath, filter, parentObs,
oldValue = eventArgs.oldValue,
value = eventArgs.value,
ctx = ev.data,
observeAll = ctx.observeAll,
cb = ctx.cb,
noArray = ctx._arOk ? 0 : 1,
paths = ctx.paths,
ns = ctx.ns;
if (ev.type === arrayChangeStr) {
(cb.array || cb).call(ctx, ev, eventArgs); // If there is an arrayHandler expando on the regular handler, use it, otherwise use the regular handler for arrayChange events also - for example: $.observe(array, handler)
// or observeAll() with an array in the graph. Note that on data-link bindings we ensure always to have an array handler - $.noop if none is specified e.g. on the data-linked tag.
} else if (ctx.prop === eventArgs.path || ctx.prop === "*") {
if (observeAll) {
allPath = observeAll._path + "." + eventArgs.path;
filter = observeAll.filter;
parentObs = [ev.target].concat(observeAll.parents());
if (isOb(oldValue)) {
observe_apply(undefined, ns, [oldValue], paths, cb, true, filter, [parentObs], allPath); // unobserve
}
if (isOb(value)) {
observe_apply(undefined, ns, [value], paths, cb, undefined, filter, [parentObs], allPath);
}
} else {
if (isOb(oldValue)) { // oldValue is an object, so unobserve
observe_apply(noArray, ns, [oldValue], paths, cb, true); // unobserve. Observe array change events too if this change is not from an 'observeAndBind' tag binding, or is from a 'depends' path
}
if (isOb(value)) { // value is an object, so observe
observe_apply(noArray, ns, [value], paths, cb); // observe. Observe array change events too if this change is not from an 'observeAndBind' tag binding, or is from a 'depends' path
}
}
ctx.cb(ev, eventArgs);
}
}
},
observe_apply = function() {
// $.observe(), but allowing you to include arrays within the arguments - which you want flattened.
var args = concat.apply([], arguments); // Flatten the arguments
return $observe.apply(args.shift(), args);
},
$observeAll = function(cb, filter, unobserve) {
observeAll(this._ns, this._data, cb, filter, [], "root", unobserve);
},
$unobserveAll = function(cb, filter) {
$observeAll.call(this, cb, filter, true);
},
observeAll = function(namespace, object, cb, filter, parentObs, allPath, unobserve, objMap) {
function observeArrayItems(arr, unobs) {
l = arr.length;
newAllPath = allPath + "[]";
while (l--) {
filterAndObserveAll(arr, l, unobs, 1);
}
}
function filterAndObserveAll(obj, prop, unobs, nestedArray) {
var newObject, newParentObs;
if ((+prop === prop || prop !== $expando) && (newObject = $observable._fltr(newAllPath, obj[prop], nextParentObs, filter))) {
newParentObs = nextParentObs.slice();
if (nestedArray && updatedTgt && newParentObs[0] !== updatedTgt) {
newParentObs.unshift(updatedTgt); // For array change events when observing an array which is not the root, need to add updated array to parentObs
}
observeAll(namespace, newObject, cb, filter || (nestedArray ? undefined : 0), newParentObs, newAllPath, unobs, objMap);
}
}
function wrappedCb(ev, eventArgs) {
// This object is changing.
allPath = ev.data.observeAll._path;
updatedTgt = ev.target;
switch (eventArgs.change) { // observeAll/unobserveAll on added or removed objects
case "insert":
observeArrayItems(eventArgs.items);
break;
case "remove":
observeArrayItems(eventArgs.items, true); // unobserveAll on removed items
break;
case "set":
newAllPath = allPath + "." + eventArgs.path;
filterAndObserveAll(eventArgs, "oldValue", true); // unobserve old value
filterAndObserveAll(eventArgs, "value"); // observe new value
}
updatedTgt = undefined;
cb.apply(this, arguments); // Observe this object (invoke the callback)
}
wrappedCb._wrp = 1;
var l, isObject, newAllPath, nextParentObs, updatedTgt, obId,
notRemoving = !objMap || objMap.un || !unobserve; // true unless it is an observeAll call (not unobserveAll) and we are removing a listener (not adding one)
if (object && typeof object === OBJECT) {
nextParentObs = [object].concat(parentObs); // The parentObs chain for the next depth of observeAll
isObject = $isArray(object) ? "" : "*";
if (objMap && notRemoving && $.hasData(object) && objMap[obId = $data(object).obId]) {
objMap[obId]++;
return; // This object has already being observed/unobserved by this observeAll/unobserveAll call (must be a cyclic object graph) so skip, to avoid
// stack overflow/multiple instances of listener. See jsviews/pull/305
// NOTE - WE DO NOT support ObserveAll on data with cyclic graphs which include DUPLICATE REFERENCES TO ARRAY PROPERTIES - such as data.children = data.descendants = []
}
if (!objMap) {
objMap = {un: unobserve}; // Map object to register observed objects for this observeAll
}
if (cb) {
// Observe this object or array - and also listen for changes to object graph, to add or remove observers from the modified object graph
if (isObject || filter !== 0) {
// If an object, observe the object. If an array, only add arrayChange binding if has filter or if filter is undefined (!== 0) - which
// is the case for top-level calls or for nested array (array item of an array - e.g. member of 2-dimensional array).
// For array properties lower in the tree, with no filter, filter is set to 0 in filterAndObserveAll, so no arrayChange binding here,
// since they get arrayChange binding added during regular $.observe(array ...) binding.
wrappedCb._cId = getCbKey(cb); // Identify wrapped callback with unwrapped callback, so unobserveAll will
// remove previous observeAll wrapped callback, if inner callback was the same;
if (notRemoving) {
$observe(namespace, object, isObject, wrappedCb, unobserve, filter, nextParentObs, allPath);
obId = $data(object).obId;
objMap[obId] = (objMap[obId] || 0) + 1; // Register on map of objects observed/unobserved by this observeAll/unobserveAll call
//- or remove from map if we are removing this object from observeAll call. (Avoid dups, for cyclic graphs)
} else {
if (--objMap[$data(object).obId]) {
// Register on map of objects observed/unobserved by this observeAll/unobserveAll call
//- or remove from map if we are removing this object from observeAll call. (Avoid dups, for cyclic graphs)
return;
}
$observe(namespace, object, isObject, wrappedCb, unobserve, filter, nextParentObs, allPath);
}
}
} else {
// No callback. Just unobserve if unobserve === true.
if (objMap) {
objMap[$data(object).obId] = 1; // Register on map of objects unobserved by this unobserveAll call. (Avoid dups, for cyclic graphs)
}
$observe(namespace, object, isObject, undefined, unobserve, filter, nextParentObs, allPath);
}
if (isObject) {
// Continue stepping through object graph, observing object and arrays
// To override filtering, pass in filter function, or replace $.observable._fltr
for (l in object) {
newAllPath = allPath + "." + l;
filterAndObserveAll(object, l, unobserve);
}
} else { // Observe items in Array
observeArrayItems(object, unobserve);
}
}
},
shallowFilter = function(path /*, object, parentObs*/) {
return rShallowPath.test(path); // No '.' and no '[' in path
},
$unobserve = function() {
[].push.call(arguments, true); // Add true as additional final argument
return $observe.apply(undefined, arguments);
},
batchTrigger = function(async) {
var event,
batch = this.slice();
this.length = 0;
this._go = 0;
while (event = batch.shift()) {
if (!event.skip) {
event[0]._trigger(event[1], event[2], true);
}
}
this.paths = {};
};
$observe = function() {
// $.observe([namespace, ]root, [1 or more objects, path or path Array params...], callback[, contextCallback][, unobserve])
function innerObserve() {
var p, parts, unobserve, callback, cbId, inId, data, contextCb, items, cbBindings,
innerCb, parentObs, allPath, filter, initNsArr, initNsArrLen, view, prop, events, el;
function unobserveBinding(cb, binding) {
var object;
for (data in binding) {
object = binding[data];
if ($isArray(object)) {
bindArray(cb, object, unobserve, unobserve);
} else {
observeOnOff(cb, object, undefined, ns, "");
}
}
}
function observeOnOff(cb, object, fullPath, namespace, pathStr, isArrayBinding, off) {
var j, evData, dataOb,
boundObOrArr = wrapArray(object),
prntObs = parentObs,
allPth = allPath;
namespace = initialNs ? namespace + "." + initialNs : namespace;
if (!unobserve && (off || isArrayBinding)) {
events = $._data(object).events;
events = events && events[isArrayBinding ? arrayChangeStr : propertyChangeStr];
el = events && events.length;
while (el--) { // Skip duplicates
data = events[el] && events[el].data;
if (data && (off && data.ns !== initialNs
// When observing, don't unbind dups unless they have the same namespace
|| !off && data.ns === initialNs && data.cb && data.cb._cId === cb._cId && data.cb._inId === cb._inId && (!cb._wrp || data.cb._wrp)))
// When observing and doing array binding, don't bind dups if they have the same namespace (Dups can happen e.g. with {^{for people ^~foo=people}})
{
return;
}
}
}
if (unobserve || off) {
$(boundObOrArr).off(namespace, onDataChange);
} else {
evData = isArrayBinding ? {}
: {
fullPath: fullPath,
paths: pathStr ? [pathStr] : [],
prop: prop,
_arOk: allowArray
};
evData.ns = initialNs;
evData.cb = cb;
if (allPath) {
// This is an observeAll call
evData.observeAll = {
_path: allPth,
path: function() { // Step through path and parentObs parent chain, replacing '[]' by '[n]' based on current index of objects in parent arrays.
j = prntObs.length;
return allPth.replace(/[[.]/g, function(all) {
j--;
return all === "["
? "[" + $.inArray(prntObs[j - 1], prntObs[j])
: ".";
});
},
parents: function() {
return prntObs; // The chain of parents between the modified object and the root object used in the observeAll() call
},
filter: filter
};
}
$(boundObOrArr).on(namespace, null, evData, onDataChange);
if (cbBindings) {
// Add object to cbBindings
dataOb = $data(object);
dataOb = dataOb.obId || (dataOb.obId = observeObjKey++);
cbBindings[dataOb] = cbBindings[dataOb] || (cbBindings.len++, object);
}
}
}
function bindArray(cb, arr, unbind, isArray, relPath) {
if (allowArray) {
// allowArray is 1 if this is a call to observe that does not come from observeAndBind (tag binding), or is from a 'depends' path,
// or for a tag with tag.onArrayChange = true - so we allow arrayChange binding. Otherwise allowArray is zero.
var object,
prevAllPath = allPath;
object = arr;
if (relPath) {
object = arr[relPath];
allPath = allPath ? allPath + "." + relPath : allPath;
}
if (filter && object) {
object = $observable._fltr(allPath, object, relPath ? [arr].concat(parentObs) : parentObs, filter);
}
if (object && (isArray || $isArray(object))) {
observeOnOff(cb, object, undefined, arrayChangeStr + ".observe" + getCbKey(cb), undefined, true, unbind);
}
allPath = prevAllPath;
}
}
function observeObjects(paths) {
function observeObjectPaths(object, pths, callback, contextCb) {
function getInnerCb(exprOb) {
exprOb.ob = contextCb(exprOb); // Initialize object
return exprOb.cb = function(ev, eventArgs) {
// The innerCb used for updating a computed in a compiled expression (setting the new instance as exprOb.ob, unobserving the previous object,
// and observing the new one), then calling the outerCB - i.e. the handler for the whole compiled expression.
// Initialized exprOb.ob to the current object.
// Uses the contextCb callback to execute the compiled exprOb template in the context of the view/data etc. to get the returned value, typically an object or array.
// If it is an array, registers array binding
// Note: For jsviews/issues/292 ctxCb will need var ctxCb = contextCb || function(exprOb, origRt) {return exprOb._cpfn(origRt);};
var obj = exprOb.ob, // The old object
sub = exprOb.sb,
newObj = contextCb(exprOb);
if (newObj !== obj) {
if (typeof obj === OBJECT) {
bindArray(callback, obj, true);
if (sub || allowArray && $isArray(obj)) {
innerObserve([obj], sub, callback, contextCb, true); // unobserve on the old object
}
}
exprOb.ob = newObj;
// Put the updated object instance onto the exprOb in the paths array, so subsequent string paths are relative to this object
if (typeof newObj === OBJECT) {
bindArray(callback, newObj);
if (sub || allowArray && $isArray(newObj)) { // observe on new object
innerObserve([newObj], sub, callback, contextCb);
}
}
}
// Call the outerCb - to execute the compiled expression that this computed is part of
callback(ev, eventArgs);
};
}
function observePath(object, prts) { // Step through the path parts "this.is^some.path" and observe changes (on the leaf, or down to the bound depth)
function obArrAddRemove(ev, eventArgs) {
// If a "[].*" or "[].prop" wild card path (for observing properties of array items) we need to observe or unobserve added or removed items
var l;
if (eventArgs.change === "insert" || (unobserve = eventArgs.change === "remove")) {
l = eventArgs.items.length;
while (l--) {
observePath(eventArgs.items[l], prts.slice());
}
unobserve = false;
}
}
if (callback) {
obArrAddRemove._cId = getCbKey(callback); // Identify wrapped callback with unwrapped callback, so unobserveAll will
// remove previous observeAll wrapped callback, if inner callback was the same;
obArrAddRemove._inId = ".arIn" + observeInnerCbKey++; // Specific _inId for each distinct obArrAddRemove, so not skipped as dups
}
var arrIndex, skip, dep, obArr, prt, fnProp, isGet,
obj = object;
if (object && object._cxp) {
return observeObjectPaths(object[0], [object[1]], callback, contextCb);
}
while ((prop = prts.shift()) !== undefined) {
if (obj && typeof obj === OBJECT && typeof prop === STRING) {
if (prop === "") {
continue;
}
if (prop.slice(-2) === "()") {
prop = prop.slice(0, -2);
isGet = true;
}
if ((prts.length < depth + 1) && !obj.nodeType) {
// Add observer for each token in path starting at depth, and on to the leaf
if (!unobserve && (events = $._data(obj).events)) {
events = events && events[propertyChangeStr];
el = events && events.length;
skip = 0;
while (el--) { // Skip duplicates
data = events[el].data;
if (data
&& data.ns === initialNs
&& data.cb._cId === callback._cId
&& data.cb._inId === callback._inId
&& !data._arOk === !allowArray
&& (data.prop === prop || data.prop === "*" || data.prop === "**")) {
if (prt = prts.join(".")) {
data.paths.push(prt); // We will skip this binding, but if it is not a leaf binding,
// need to keep bindings for rest of path, ready for if the obj gets swapped.
}
skip++;
}
}
if (skip) {
// Duplicate binding(s) found, so move on
fnProp = obj[prop];
obj = $isFunction(fnProp) ? fnProp.call(obj) : obj[prop];
continue;
}
}
if (prop === "*" || prop === "**") { // "*" => all properties. "**" => all properties and sub-properties (i.e. deep observeAll behavior)
if (!unobserve && events && events.length) {
// Remove existing bindings, since they will be duplicates with "*" or "**"
observeOnOff(callback, obj, path, ns, "", false, true);
}
if (prop === "*") {
observeOnOff(callback, obj, path, ns, ""); // observe the object for any property change
for (prt in obj) {
// observing "*": So (in addition to listening to prop change, above) listen to arraychange on props of type array
if (prt !== $expando) {
bindArray(callback, obj, unobserve, undefined, prt);
}
}
} else {
$.observable(initialNs, obj)[(unobserve ? "un" : "") + "observeAll"](callback); // observe or unobserve the object for any property change
}
break;
} else if (prop == "[]") { // "[].*" or "[].prop" wild card path, for observing properties of array items
if ($isArray(obj)) {
if (unobserve) {
observeOnOff(callback, obj, path, arrayChangeStr + getCbKey(callback), undefined, unobserve, unobserve);
} else {
$observe(initialNs, obj, obArrAddRemove, unobserve); // observe or unobserve added or removed items
}
}
} else if (prop) {
observeOnOff(callback, obj, path, ns + ".p_" + prop, prts.join("^")); // By using "^" rather than "." we ensure that deep binding will be used on newly inserted object graphs
}
}
if (allPath) {
allPath += "." + prop;
}
if (prop === "[]") {
if ($isArray(obj)) {
obArr = obj;
arrIndex = obj.length;
}
while (arrIndex--) {
obj = obArr[arrIndex];
observePath(obj, prts.slice());
}
return;
}
prop = obj[prop];
if (!prts[0]) {
bindArray(callback, prop, unobserve); // [un]observe(object, "arrayProperty") observes array changes on property of type array
}
}
if ($isFunction(prop)) {
fnProp = prop;
if (dep = fnProp.depends) {
// This is a computed observable. We will observe any declared dependencies.
if (obj._vw && obj._ocp) {
// Observable contextual parameter, so context was ocp object. Now move context to view.data for dependencies
obj = obj._vw; // storeView or tag (scope of contextual parameter)
if (obj._tgId) {
// Is a tag, so get view
obj = obj.tagCtx.view;
}
obj = obj.data; // view.data
}
observeObjects(concat.apply([], [[obj], dependsPaths(dep, obj, callback)]));
}
if (isGet) {
if (!prts[0]) {
bindArray(callback, fnProp.call(obj), unobserve);
break;
}
prop = fnProp.call(obj);
if (!prop) {
break;
}
}
}
obj = prop;
}
}
var i, path,
depth = 0,
l = pths.length;
if (object && !contextCb && ((view = object._is === "view") || object._is === "tag")) {
contextCb = $sub._gccb(view ? object : object.tagCtx.contentView);
if (callback && !unobserve) {
(function() {
var ob = object,
cb = callback;
callback = function(ev, eventArgs) {
// Wrapped callback so this pointer is tag or view
cb.call(ob, ev, eventArgs);
};
callback._cId = cb._cId;
callback._inId = cb._inId;
})();
}
object = view ? object.data : object;
}
if (!pths[0]) {
if ($isArray(object)) {
bindArray(callback, object, unobserve, true); // observe(array, handler)
} else if (unobserve) {
observeOnOff(callback, object, undefined, ns, ""); // unobserve(objectOrArray[, handler])
}
}
for (i = 0; i < l; i++) { // Step through objects and paths
path = pths[i];
if (path === "") {
continue;
}
if (path && path._ar) {
allowArray += path._ar; // Switch on allowArray for depends paths, and off, afterwards.
continue;
}
if (typeof path === STRING) {
parts = path.split("^");
if (parts[1]) {
// We bind the leaf, plus additional nodes based on depth.
// "a.b.c^d.e" is depth 2, so listens to changes of e, plus changes of d and of c
depth = parts[0].split(".").length;
path = parts.join(".");
depth = path.split(".").length - depth;
// if more than one ^ in the path, the first one determines depth
}
if (contextCb && (items = contextCb(path, depth))) {
//object, paths
if (items.length) {
var ob = items[0],
pth = items[1];
if (ob && ob._cxp) { // contextual parameter
pth = ob[1];
ob = ob[0];
if (ob._is === "view") {
observeObjectPaths(ob, [pth], callback); // Setting contextCb to undefined, to use passed in view for new contextCb
continue;
}
}
if (typeof pth === STRING) {
observePath(ob, pth.split("."));
} else {
observeObjectPaths(items.shift(), items, callback, contextCb);
}
}
} else {
observePath(object, path.split("."));
}
} else if (!$isFunction(path) && path && path._cpfn) {
// Path is an exprOb returned by a computed property - helper/data function (compiled expr function).
// Get innerCb for updating the object
innerCb = unobserve ? path.cb : getInnerCb(path);
// innerCb._ctx = callback._ctx; Could pass context (e.g. linkCtx) for use in a depends = function() {} call, so depends is different for different linkCtx's
innerCb._cId = callback._cId;
// Set the same cbBindingsStore key as for callback, so when callback is disposed, disposal of innerCb happens too.
innerCb._inId = innerCb._inId || ".obIn" + observeInnerCbKey++;
if (path.bnd || path.prm && path.prm.length || !path.sb) {
// If the exprOb is bound e.g. foo()^sub.path, or has parameters e.g. foo(bar) or is a leaf object (so no sub path) e.g. foo()
// then observe changes on the object, or its parameters and sub-path
innerObserve([object], path.path, (path.prm.length ? [path.root||object] : []), path.prm, innerCb, contextCb, unobserve);
}
if (path.sb) { // Has a subPath
// Observe changes on the sub-path
if (path.sb.prm) {
path.sb.root = object;
}
// Set current object on exprOb.ob
observeObjectPaths(path.ob, [path.sb], callback, contextCb);
}
}
}
}
var pth,
pths = [], // Array of paths for current object
l = paths.length;
while (l--) { // Step backwards through paths and objects
pth = paths[l];
if (typeof pth === STRING || pth && (pth._ar || pth._cpfn)) {
pths.unshift(pth); // This is a path so add to arr
} else { // This is an object
observeObjectPaths(pth, pths, callback, contextCb);
pths = []; // New array for next object
}
}
}
//END OF FUNCTIONS
var ns = observeStr,
paths = this != 1 // Using != for IE<10 bug- see jsviews/issues/237
? concat.apply([], arguments) // Flatten the arguments - this is a 'recursive call' with params using the 'wrapped array'
// style - such as innerObserve([object], path.path, [origRoot], path.prm, innerCb, ...);
: slice.call(arguments), // Don't flatten - this is the first 'top-level call, to innerObserve.apply(1, paths)
lastArg = paths.pop() || false,
m = paths.length;
if (typeof lastArg === STRING) { // If last arg is a string then this observe call is part of an observeAll call,
allPath = lastArg; // and the last three args are the parentObs array, the filter, and the allPath string.
parentObs = paths.pop();
filter = paths.pop();
lastArg = !!paths.pop(); // unobserve
m -= 3;
}
if (lastArg === !!lastArg) {
unobserve = lastArg;
lastArg = paths[m-1];
lastArg = m && typeof lastArg !== STRING && (!lastArg || $isFunction(lastArg)) ? (m--, paths.pop()) : undefined;
if (unobserve && !m && $isFunction(paths[0])) {
lastArg = paths.shift();
}
}
callback = lastArg;
if (m && $isFunction(paths[m - 1])) {
contextCb = callback;
lastArg = callback = paths.pop();
m--;
}
if (unobserve && callback && !callback._cId) {
return;
}
// Use a unique namespace (e.g. obs7) associated with each observe() callback to allow unobserve to remove handlers
ns += callback
? ((inId = callback._inId || ""), unobserve)
? callback._cId + inId
: (cbId = getCbKey(callback)) + inId
: "";
if (cbId && !unobserve) {
cbBindings = cbBindingsStore[cbId] = cbBindingsStore[cbId] || {len: 0};
}
initNsArr = initialNs && initialNs.match(rNotWhite) || [""];
initNsArrLen = initNsArr.length;
while (initNsArrLen--) { // Step through multiple white-space separated namespaces if there are any
initialNs = initNsArr[initNsArrLen];
if (unobserve && arguments.length < 3) {
if (callback) {
unobserveBinding(callback, cbBindingsStore[callback._cId]); // unobserve(handler) - unobserves this handler, all objects
} else if (!paths[0]) {
for (p in cbBindingsStore) {
unobserveBinding(callback, cbBindingsStore[p]); // unobserve() - unobserves all
}
}
}
observeObjects(paths);
}
if (cbId && !cbBindings.len) {
// If the cbBindings collection is empty we will remove it from the cbBindingsStore
delete cbBindingsStore[cbId];
}
// Return the cbBindings to the top-level caller, along with the cbId
return {cbId: cbId, bnd: cbBindings, s: cbBindingsStore};
}
var initialNs,
allowArray = this == 1 ? 0 : 1, // If this == 1, this is a call from observeAndBind (doing binding of datalink expressions),
// and tag.onArrayChange is not set to true. We don't bind arrayChange events in this scenario. Instead, {^{for}} and similar
// do specific arrayChange binding to the tagCtx.args[0] value, in onAfterLink.
// Note deliberately using this == 1, rather than this === 1 because of IE<10 bug - see jsviews/issues/237
paths = slice.call(arguments),
pth = paths[0];
if (typeof pth === STRING) {
initialNs = pth; // The first arg is a namespace, since it is a string
paths.shift();
}
return innerObserve.apply(1, paths);
};
asyncBatch.wait = function() {
var batch = this;
batch._go = 1;
setTimeout(function() {
batch.trigger(true);
batch._go = 0;
batch.paths = {};
});
};
$observable = function(ns, data, delay) {
if (typeof ns !== STRING) {
delay = data;
data = ns;
ns = "";
}
delay = delay === undefined ? $subSettingsAdvanced.asyncObserve : delay;
var observable = $isArray(data)
? new ArrayObservable(ns, data)
: new ObjectObservable(ns, data);
if (delay) {
if (delay === true) {
observable.async = true;
delay = asyncBatch;
}
if (!delay.trigger) {
if ($isArray(delay)) {
delay.trigger = batchTrigger;
delay.paths = {};
} else {
delay = undefined;
}
}
observable._batch = delay;
}
return observable;
};
//========================== Initialize ==========================
$.observable = $observable;
$observable._fltr = function(path, object, parentObs, filter) {
if (filter && $isFunction(filter)
? filter(path, object, parentObs)
: true // TODO Consider supporting filter being a string or strings to do RegEx filtering based on key and/or path
) {
object = $isFunction(object)
? object.set && object.call(parentObs[0]) // It is a getter/setter
: object;
return typeof object === OBJECT && object;
}
};
$observable.Object = ObjectObservable;
$observable.Array = ArrayObservable;
$.observe = $observable.observe = $observe;
$.unobserve = $observable.unobserve = $unobserve;
$observable._apply = observe_apply;
ObjectObservable.prototype = {
_data: null,
observeAll: $observeAll,
unobserveAll: $unobserveAll,
data: function() {
return this._data;
},
setProperty: function(path, value, nonStrict, isCpfn) {
path = path || "";
var key, pair, parts, tempBatch,
multi = typeof path !== STRING, // Hash of paths
self = this,
object = self._data,
batch = self._batch;
if (object) {
if (multi) {
nonStrict = value;
if ($isArray(path)) {
// This is the array format generated by serializeArray. However, this has the problem that it coerces types to string,
// and does not provide simple support of convertTo and convertFrom functions.
key = path.length;
while (key--) {
pair = path[key];
self.setProperty(pair.name, pair.value, nonStrict === undefined || nonStrict); //If nonStrict not specified, default to true;
}
} else {
if (!batch) {
self._batch = tempBatch = [];
tempBatch.trigger = batchTrigger;
tempBatch.paths = {};
}
for (key in path) { // Object representation where property name is path and property value is value.
self.setProperty(key, path[key], nonStrict);
}
if (tempBatch) {
self._batch.trigger();
self._batch = undefined;
}
}
} else if (path !== $expando) {
// Simple single property case.
parts = path.split(/[.^]/);
while (object && parts.length > 1) {
object = object[parts.shift()];
}
if (object) {
self._setProperty(object, parts[0], value, nonStrict, isCpfn);
}
}
}
return self;
},
removeProperty: function(path) {
this.setProperty(path, remove);
return this;
},
_setProperty: function(leaf, path, value, nonStrict, isCpfn) {
var setter, getter, removeProp, eventArgs, view,
property = path ? leaf[path] : leaf;
if ($isFunction(property) && !$isFunction(value)) {
if (isCpfn && !property.set) {
return; // getter function with no setter defined. So will not trigger update
} else if (property.set) {
// Case of property setter/getter - with convention that property is getter and property.set is setter
view = leaf._vw // Case of JsViews 2-way data-linking to an observable context parameter, with a setter.
// The view will be the this pointer for getter and setter. Note: this is the one scenario where path is "".
|| leaf;
getter = property;
setter = getter.set === true ? getter : getter.set;
property = getter.call(view); // get - only treated as getter if also a setter. Otherwise it is simply a property of type function.
// See unit tests 'Can observe properties of type function'.
}
}
if (property !== value || nonStrict && property != value) {
// Optional non-strict equality, since serializeArray, and form-based editors can map numbers to strings, etc.
// Date objects don't support != comparison. Treat as special case.
if (!(property instanceof Date && value instanceof Date) || property > value || property < value) {
if (setter) {
setter.call(view, value); // set
value = getter.call(view); // get updated value
} else if (removeProp = value === remove) {
if (property !== undefined) {
delete leaf[path];
value = undefined;
} else {
path = undefined; // If value was already undefined, don't trigger handler for removeProp
}
} else if (path) {
leaf[path] = value;
}
if (path) {
eventArgs = {change: "set", path: path, value: value, oldValue: property, remove: removeProp};
if (leaf._ocp) {
eventArgs.ctxPrm = leaf._key;
}
this._trigger(leaf, eventArgs);
}
}
}
},
_trigger: function(target, eventArgs, force) {