forked from finnsson/pagerjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pager.js
1519 lines (1369 loc) · 52 KB
/
pager.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 (window) {
var pagerJsModule = function ($, ko) {
"use strict";
/**
* @module pager
* @readme README.md
*/
/**
*
* @param fn
* @param scope
* @return {Function}
*/
var makeComputed = function (fn, scope) {
return function () {
var args = arguments;
return ko.computed(function () {
return fn.apply(scope, args);
});
};
};
var pager = {};
pager.page = null;
pager.now = function () {
if (!Date.now) {
return (new Date()).valueOf();
} else {
return Date.now();
}
};
/**
* @method extendWithPage
* @static
* @param {Observable} viewModel
*/
pager.extendWithPage = function (viewModel) {
var page = new pager.Page();
viewModel['$__page__'] = page;
pager.page = page;
// initialize computed observables that depend on pager.page
pager.activePage$ = makeComputed(pager.getActivePage, pager)();
};
var fire = function (scope, name, options) {
options = options || {};
options.page = scope;
// first fire the global method
pager[name].fire(options);
// then call the local callback
if (scope.val(name)) {
scope.val(name)(options);
}
};
// Add 9 callbacks on pager
$.each(['onBindingError', 'onSourceError', 'onNoMatch', 'onMatch',
'beforeRemove', 'afterRemove',
'beforeHide', 'afterHide',
'beforeShow', 'afterShow'], function (i, n) {
pager[n] = $.Callbacks();
});
/**
*
* @param {String[]} route
*/
pager.showChild = function (route) {
// trim empty array
var trimmedRoute = (route && route.length === 1 && route[0] === '') ? [] : route;
pager.page.showPage(trimmedRoute);
};
pager.getParentPage = function (bindingContext) {
// search this context/$data until either root is accessed or no page is found
while (bindingContext) {
// get first parent page, but exclude pages with urlToggle: none
if (bindingContext.$page && bindingContext.$page.val('urlToggle') !== 'none') {
return bindingContext.$page;
} else if (bindingContext.$data && bindingContext.$data.$__page__) {
return bindingContext.$data.$__page__;
}
bindingContext = bindingContext.$parentContext;
}
return null;
};
// set this to a random value in order to verify that the navigation should happen
// Is cleaned after every goTo.
var goToKey = null;
var currentAsyncDeferred = null;
/**
*
* Takes a complete, working, path as parameter. *Not* a route, relative route or Page-object.
*
* @param {String} path
*/
var goTo = function (path) {
// reject any async navigation in progress
if (currentAsyncDeferred) {
currentAsyncDeferred.reject({cancel: true});
}
goToKey = null;
// strip # (or #!/)
if (path.substring(0, pager.Href.hash.length) === pager.Href.hash) {
path = path.slice(pager.Href.hash.length);
}
// split on '/' and decode
var hashRoute = parseHash(path);
// trigger navigation
pager.showChild(hashRoute);
};
pager.goTo = goTo;
/**
*
* navigate takes a complete, working, path as parameter. *NOT* a route, object or pager.Page-object.
*
* @param {String} path
*/
pager.navigate = function (path) {
if (pager.useHTML5history) {
pager.Href5.history.pushState(null, null, path);
} else {
location.hash = path;
}
};
var parseHash = function (hash) {
return $.map(hash.replace(/\+/g, ' ').split('/'), decodeURIComponent);
};
// common KnockoutJS helpers
var _ko = {};
_ko.value = ko.utils.unwrapObservable;
_ko.arrayValue = function (arr) {
return $.map(arr, function (e) {
return _ko.value(e);
});
};
var parseStringAsParameters = function (query) {
var match,
urlParams = {},
search = /([^&=]+)=?([^&]*)/g;
while (match = search.exec(query)) {
urlParams[match[1]] = match[2];
}
return urlParams;
};
var splitRoutePartIntoNameAndParameters = function (routePart) {
if (!routePart) {
return {name: null, params: {}};
}
var routeSplit = routePart.split('?');
var name = routeSplit[0];
var paramsString = routeSplit[1];
var params = {};
if (paramsString) {
params = parseStringAsParameters(paramsString);
}
return {
name: name,
params: params
};
};
/**
* @class pager.ChildManager
*
* @param {pager.Page[]} children
* @param {pager.Page} page
*/
pager.ChildManager = function (children, page) {
this.currentChildO = ko.observable(null);
var me = this;
this.page = page;
// Used by showChild to find out if the navigation is still current.
// In needed since the navigation is asynchronous and another navigation might happen in between.
this.timeStamp = pager.now();
/**
* @method pager.ChildManager#hideChild
*/
this.hideChild = function () {
var currentChild = me.currentChildO();
if (currentChild) {
currentChild.hidePage(function () {
});
me.currentChildO(null);
}
};
/**
* Show the sub-page in this ChildManager's page that matches the route.
*
* @method pager.ChildManager#showChild
* @param {String[]} route route to match a sub-page to. Can be on the form `['foo','bar?x=22&y=11']`.
*/
this.showChild = function (route) {
var showOnlyStart = route.length === 0;
this.timeStamp = pager.now();
var timeStamp = this.timeStamp;
var oldCurrentChild = me.currentChildO();
var currentChild = null;
var match = false;
var currentRoutePair = splitRoutePartIntoNameAndParameters(route[0]);
var currentRoute = currentRoutePair.name;
var wildcard = null;
$.each(children(), function (childIndex, child) {
if (!match) {
var id = child.getId();
if (id === currentRoute ||
((currentRoute === '' || currentRoute == null) && child.isStartPage())) {
match = true;
currentChild = child;
}
if (id === '?') {
wildcard = child;
}
}
});
// find modals in parent - but only if 1) no match is found, 2) this page got a parent and 3) this page is not a modal!
var isModal = false;
var currentChildManager = me;
var findMatchModalOrWildCard = function (childIndex, child) {
if (!match) {
var id = child.getId();
var modal = child.getValue().modal;
if (modal) {
if (id === currentRoute ||
((currentRoute === '' || currentRoute == null) && child.isStartPage())) {
match = true;
currentChild = child;
isModal = true;
}
if (id === '?' && !wildcard) {
wildcard = child;
isModal = true;
}
}
}
};
while (!currentChild && currentChildManager.page.parentPage && !currentChildManager.page.getValue().modal) {
var parentChildren = currentChildManager.page.parentPage.children;
$.each(parentChildren(), findMatchModalOrWildCard);
if (!currentChild) {
currentChildManager = currentChildManager.page.parentPage.childManager;
}
}
if (!currentChild && wildcard && !showOnlyStart) {
currentChild = wildcard;
//me.currentChild.currentId = currentRoute;
}
me.currentChildO(currentChild);
if (currentChild) {
if (isModal) {
currentChild.currentParentPage(me.page);
} else {
currentChild.currentParentPage(null);
}
}
var onFailed = function () {
fire(me.page, 'onNoMatch', {route: route});
};
var showCurrentChild = function () {
fire(me.page, 'onMatch', {route: route});
var guard = _ko.value(currentChild.getValue().guard);
if (guard) {
guard(currentChild, route, function () {
if (me.timeStamp === timeStamp) {
currentChild.showPage(route.slice(1), currentRoutePair, route[0]);
}
}, oldCurrentChild);
} else {
currentChild.showPage(route.slice(1), currentRoutePair, route[0]);
}
};
if (oldCurrentChild && oldCurrentChild === currentChild) {
showCurrentChild();
} else if (oldCurrentChild) {
oldCurrentChild.hidePage(function () {
if (currentChild) {
showCurrentChild();
} else {
onFailed();
}
});
} else if (currentChild) {
showCurrentChild();
} else {
onFailed();
}
};
};
/**
*
* @class pager.Page
*
* @constructor
*
* @param {Node} element
* @param {Object} valueAccessor
* @param {String} valueAccessor.id
* @param {Observable} valueAccessor.with
* @param {Function} valueAccessor.withOnShow
* @param {String/Function} valueAccessor.source
* @param {String/Function} valueAccessor.sourceLoaded
* @param {Number/Boolean} valueAccessor.sourceCache
* @param {String} valueAccessor.frame
* @param {Boolean} valueAccessor.modal
* @param {Boolean} valueAccessor.deep
* @param {Function} valueAccessor.beforeHide
* @param {Function} valueAccessor.beforeShow
* @param {Function} valueAccessor.afterHide
* @param {Function} valueAccessor.hideElement
* @param {Function} valueAccessor.showElement
* @param {Function} valueAccessor.loader
* @param {Function} valueAccessor.onNoMatch
* @param {Function} valueAccessor.guard
* @param {Object} valueAccessor.params
* @param {Object} valueAccessor.vars
* @param {String} valueAccessor.fx
* @param {String} valueAccessor.urlToggle can be either null (default), "none" or "show"
* @param allBindingsAccessor
* @param {Observable} viewModel
* @param bindingContext
*/
pager.Page = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
/**
*
* @type {Node}
*/
this.element = element;
/**
*
* @type {Observable}
*/
this.valueAccessor = valueAccessor;
/**
*
* @type {*}
*/
this.allBindingsAccessor = allBindingsAccessor;
/**
*
* @type {Observable}
*/
this.viewModel = viewModel;
/**
*
* @type {*}
*/
this.bindingContext = bindingContext;
/**
*
* @type {ObservableArray}
*/
this.children = ko.observableArray([]);
/**
*
* @type {pager.ChildManager}
*/
this.childManager = new pager.ChildManager(this.children, this);
/**
*
* @type {pager.Page}
*/
this.parentPage = null;
/**
*
* @type {String}
*/
this.currentId = null;
this.getCurrentId = ko.observable();
/**
*
*
* @type {Observable}
*/
this.ctx = null;
/**
*
* @type {Observable/pager.Page}
*/
this.currentParentPage = ko.observable(null);
/**
*
* @type {Observable}
*/
this.isVisible = ko.observable(false);
this.originalRoute = ko.observable(null);
this.route = null;
};
var p = pager.Page.prototype;
/**
* @method pager.Page#val
*
* @param {String} key
* @return {Object} an un-boxed configuration property
*/
p.val = function (key) {
return _ko.value(this.getValue()[key]);
};
/**
* @method pager.Page#currentChildPage
*
* Returns an observable to the child page.
*
* @returns {Observable}
*/
p.currentChildPage = function () {
return this.childManager.currentChildO;
};
/**
*
* @param {String} key relative (to this page) or absolute page path
* @return {Observable} page
*/
p.find = function (key) {
var k = _ko.value(key);
var currentRoot = this;
if (k.substring(0, 1) === '/') {
currentRoot = pager.page;
k = k.slice(1);
} else {
while (k.substring(0, 3) === '../') {
currentRoot = (currentRoot.currentParentPage && currentRoot.currentParentPage()) ?
currentRoot.currentParentPage() :
currentRoot.parentPage;
k = k.slice(3);
}
}
var route = parseHash(k);
$.each(route, function (_, r) {
currentRoot = currentRoot.child(r)();
});
return currentRoot;
};
p.find$ = function (key) {
return makeComputed(this.find, this)(key);
};
var absolutePathToRealPath = function (path) {
if (pager.useHTML5history) {
return $('base').attr('href') + path;
} else {
return pager.Href.hash + path;
}
};
/**
*
* Utility method to generate a complete (computed observable) path relative to the current Page.
*
* @param {String/pager.Page/Object} path can either be relative path, a Page-object or a {path: params:}-object.
* @return {String}
*/
p.path = function (path) {
var me = this;
var p = _ko.value(path);
if (p && typeof(p) === 'object' && p.path && p.params && !(p instanceof pager.Page)) {
var objectPath = p.path;
var params = p.params;
return me.path(objectPath) + '?' + $.param(params);
} else {
var page;
if (p == null || p === '') {
page = me;
} else if (p instanceof pager.Page) {
page = p;
} else { // if string
if (p.substring(0, 1) === '/') {
var pagePath = pager.page.getFullRoute()().join('/') + p.substring(1);
return absolutePathToRealPath(pagePath);
}
var parentsToTrim = 0;
while (p.substring(0, 3) === '../') {
parentsToTrim++;
p = p.slice(3);
}
var fullRoute = me.getFullRoute()();
var parentPath = fullRoute.slice(0, fullRoute.length - parentsToTrim).join('/');
var fullPathWithoutHash = (parentPath === '' ? '' : parentPath + '/') + p;
return absolutePathToRealPath(fullPathWithoutHash);
}
return absolutePathToRealPath(page.getFullRoute()().join('/'));
}
};
p.path$ = function (path) {
return makeComputed(this.path, this)(path);
};
/**
*
* @param {Function} fn should return a $.Deferred (NOT a promise since async should be able to reject it).
* @param {String/Object} ok route (e.g. '/some/path' or '../some/path'). Should not contain '#!/'.
* @param {String/Object} notOk route (e.g. '/some/path' or '../some/path'). Should not contain '#!/'.
* @param {Function} [state]
* @return {Function}
*/
p.async = function (fn, ok, notOk, state) {
var me = this;
return function () {
if (currentAsyncDeferred) {
currentAsyncDeferred.reject({cancel: true});
}
var result = fn();
currentAsyncDeferred = result;
if (state) {
state(result.state());
}
var key = Math.random();
goToKey = key;
result.done(function () {
if (state) {
state(result.state());
}
if (key === goToKey) {
pager.navigate(me.path(ok));
}
});
result.fail(function (data) {
if (state) {
state(result.state());
}
var cancel = data && data.cancel;
if (key === goToKey) {
if (!cancel && notOk) {
pager.navigate(me.path(notOk));
}
}
});
};
};
/**
* @method showPage
* @member pager.Page
*
* @param route
* @param [pageRoute]
* @param [originalRoute]
*/
p.showPage = function (route, pageRoute, originalRoute) {
var m = this,
currentId = m.currentId,
params = m.pageRoute ? m.pageRoute.params : null,
isVisible = m.isVisible();
m.currentId = pageRoute ? (pageRoute.name || '') : '';
m.getCurrentId(m.currentId);
m.isVisible(true);
if (originalRoute) {
m.originalRoute(originalRoute);
}
m.route = route;
m.pageRoute = pageRoute;
// show if not already visible
if (!isVisible) {
m.setParams();
m.show();
} else {
// show if wildcard got new ID
if (m.getId() === '?' && currentId !== m.currentId) {
m.show();
}
// update params if they are updated
if (pageRoute && params !== pageRoute.params) {
m.setParams();
}
}
m.childManager.showChild(route);
};
/**
* @method setParams
* @member pager.Page
*
*/
p.setParams = function () {
if (this.pageRoute && this.pageRoute.params) {
var params = this.pageRoute.params;
// get view model
var vm = this.ctx;
var userParams = this.val('params') || {};
// for each param for URL
if ($.isArray(userParams)) {
$.each(userParams, function (index, key) {
var value = params[key];
if (vm[key]) { // set observable ...
vm[key](value);
} else { // ... or create observable
vm[key] = ko.observable(value);
}
});
} else {
$.each(userParams, function (key, defaultValue) {
var value = params[key];
var runtimeValue;
if (value == null) {
runtimeValue = _ko.value(defaultValue);
} else {
runtimeValue = value;
}
if (vm[key]) {
vm[key](runtimeValue);
} else {
vm[key] = ko.observable(runtimeValue);
}
});
}
}
if (this.pageRoute) {
var nameParam = this.getValue()['nameParam'];
if (nameParam) {
if (typeof nameParam === 'string') {
if (this.ctx[nameParam]) { // set observable ...
this.ctx[nameParam](this.currentId);
} else { // ... or create observable
this.ctx[nameParam] = ko.observable(this.currentId);
}
} else { // is Observable
nameParam(this.currentId);
}
}
}
};
/**
* @method hidePage
* @member pager.Page
*
* @param {Function} callback
*/
p.hidePage = function (callback) {
var m = this;
if ('show' !== m.val('urlToggle')) {
m.hideElementWrapper(callback);
m.childManager.hideChild();
} else {
if (callback) {
callback();
}
}
};
var applyBindingsToDescendants = function (page) {
try {
ko.applyBindingsToDescendants(page.childBindingContext, page.element);
} catch (e) {
if(!pager.onBindingError.has()) {
if(window.console && window.console.error) {
window.console.error(e);
}
}
fire(page, 'onBindingError', {error: e});
}
};
/**
* @method init
* @member pager.Page
*
* @return {Object}
*/
p.init = function () {
var m = this;
m.cleanElement = m.element.innerHTML;
var urlToggle = m.val('urlToggle');
var id = m.val('id');
if (id !== '?') {
m.getCurrentId(id);
}
var existingPage = ko.utils.domData.get(m.element, '__ko_pagerjsBindingData');
if (existingPage) {
return { controlsDescendantBindings: true};
} else {
ko.utils.domData.set(m.element, '__ko_pagerjsBindingData', m);
}
// listen to when the element is removed
ko.utils.domNodeDisposal.addDisposeCallback(m.element, function () {
// then remove this Page-instance
fire(m, 'beforeRemove');
if (m.parentPage) {
m.parentPage.children.remove(m);
}
fire(m, 'afterRemove');
});
var value = m.getValue();
if (urlToggle !== 'none') {
m.parentPage = m.getParentPage();
m.parentPage.children.push(this);
m.hideElement();
}
// Fetch source
if (m.val('source')) {
m.loadSource(m.val('source'));
}
m.ctx = null;
if (value.withOnShow) {
m.ctx = {};
m.childBindingContext = m.bindingContext.createChildContext(m.ctx);
ko.utils.extend(m.childBindingContext, { $page: this });
} else {
var context = value['with'] || m.bindingContext['$observableData'] || m.viewModel;
m.ctx = _ko.value(context);
m.augmentContext();
if (ko.isObservable(context)) {
var dataInContext = ko.observable(m.ctx);
m.childBindingContext = m.bindingContext.createChildContext(dataInContext);
ko.utils.extend(m.childBindingContext, {
$page: this,
$observableData: context
});
applyBindingsToDescendants(m);
context.subscribe(function () {
dataInContext(_ko.value(context));
});
} else {
m.childBindingContext = m.bindingContext.createChildContext(m.ctx);
ko.utils.extend(m.childBindingContext, {
$page: this,
$observableData: undefined
});
applyBindingsToDescendants(m);
}
}
if (urlToggle !== 'none') {
// check if this page should trigger showChild at parent
var parent = m.parentPage;
if (parent.route && (parent.route[0] === m.getId() || (parent.route.length && m.getId() === '?') )) {
// call once the current event loop is finished.
setTimeout(function () {
parent.showPage(parent.route);
}, 0);
}
} else { // urlToggle === 'none'
// when the page is rendered
var display = function () {
// if the page is visible
if ($(m.element).is(':visible')) {
// trigger showPage with empty route-array
m.showPage([]);
}
};
setTimeout(display, 0);
m.getParentPage().isVisible.subscribe(function (x) {
if (x) {
setTimeout(display, 0);
}
});
}
// Bind the page to the config property `bind` if it exists
var bind = m.getValue()['bind'];
if (ko.isObservable(bind)) {
bind(m);
}
return { controlsDescendantBindings: true };
};
p.augmentContext = function () {
var m = this;
var params = m.val('params');
if (params) {
if ($.isArray(params)) {
$.each(params, function (index, param) {
if (!m.ctx[param]) {
m.ctx[param] = ko.observable();
}
});
} else { // is object
$.each(params, function (key, value) {
if (!m.ctx[key]) {
if (ko.isObservable(value)) {
m.ctx[key] = value;
} else if (value === null) {
params[key] = ko.observable(null);
m.ctx[key] = ko.observable(null);
} else {
m.ctx[key] = ko.observable(value);
}
}
});
}
}
if (this.val('vars')) {
$.each(this.val('vars'), function (key, value) {
if (ko.isObservable(value)) {
m.ctx[key] = value;
} else {
m.ctx[key] = ko.observable(value);
}
});
}
var nameParam = this.getValue()['nameParam'];
if (nameParam && typeof nameParam === 'string' && !m.ctx[nameParam]) {
m.ctx[nameParam] = ko.observable(null);
}
this.setParams();
};
/**
* @method pager.Page#getValue
* @returns {Object} value
*/
p.getValue = function () {
if (this.valueAccessor) {
return _ko.value(this.valueAccessor());
} else {
return {};
}
};
/**
* @method pager.Page#getParentPage
* @return {pager.Page}
*/
p.getParentPage = function () {
return pager.getParentPage(this.bindingContext);
};
/**
* @method pager.Page#getId
* @return String
*/
p.getId = function () {
return this.val('id');
};
p.id = function () {
var currentId = this.getCurrentId();
if (currentId == null || currentId === '') {
return this.getId();
} else {
return currentId;
}
};
/**
* @method pager.Page#sourceUrl
*
* @param {Observable/String} source
* @return {Observable}
*/
p.sourceUrl = function (source) {
var me = this;
if (this.getId() === '?') {
return ko.computed(function () {
// TODO: maybe make currentId an ko.observable?
var path;
if (me.val('deep')) {
path = [me.currentId].concat(me.route).join('/');
} else {
path = me.currentId;
}
return _ko.value(source).replace('{1}', path);
});
} else {
return ko.computed(function () {
return _ko.value(source);
});
}
};
p.loadWithOnShow = function () {
var me = this;
if (!me.withOnShowLoaded || me.val('sourceCache') !== true) {
me.val('withOnShow')(function (vm) {
if (!me.val('sourceOnShow') && me.withOnShowLoaded) {
ko.cleanNode($(me.element));
$(me.element).empty();
me.element.innerHTML = me.cleanElement;
}
var childBindingContext = me.bindingContext.createChildContext(vm);
me.ctx = vm;
// replace the childBindingContext
me.childBindingContext = childBindingContext;
me.augmentContext();
ko.utils.extend(childBindingContext, {$page: me});
applyBindingsToDescendants(me);
// what is signaling if a page is active or not?
if (me.route) {
me.childManager.showChild(me.route);
}
}, me);
me.withOnShowLoaded = true;
}
};
/**
* @method pager.Page#loadSource
* @param source
*/
p.loadSource = function (source) {
var value = this.getValue();
var me = this;
var element = this.element;
var loader = null;
var loaderMethod = value.loader || pager.loader;
if (value.frame === 'iframe') {
var iframe = $('iframe', $(element));
if (iframe.length === 0) {
iframe = $('<iframe></iframe>');
$(element).append(iframe);
}
if (loaderMethod) {
loader = _ko.value(loaderMethod)(me, iframe);
loader.load();
}
iframe.one('load', function () {
if (loader) {
loader.unload();
}
if (value.sourceLoaded) {
value.sourceLoaded(me);
}
});
// TODO: remove src binding and add this binding
ko.applyBindingsToNode(iframe[0], {
attr: {
src: this.sourceUrl(source)
}
});
} else {
if (loaderMethod) {
loader = _ko.value(loaderMethod)(me, me.element);
loader.load();
}
// TODO: remove all children and add sourceUrl(source)
var onLoad = function () {
// remove load
if (loader) {
loader.unload();
}
// apply bindings
// TODO: call abstraction that either applies binding or loads view-model
if (!me.val('withOnShow')) {