-
Notifications
You must be signed in to change notification settings - Fork 114
/
jquery-mobile-angular-adapter-1.2.1-SNAPSHOT.js
2249 lines (2049 loc) · 83.7 KB
/
jquery-mobile-angular-adapter-1.2.1-SNAPSHOT.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
/**
* jQuery Mobile angularJS adaper v1.2.1-SNAPSHOT
* http://github.com/tigbro/jquery-mobile-angular-adapter
*
* Copyright 2011, Tobias Bosch (OPITZ CONSULTING GmbH)
* Licensed under the MIT license.
*/
(function(factory) {
if (typeof define === "function" && define.amd) {
define(["jquery", "angular", "jquery.mobile"], factory);
} else {
factory(window.jQuery, window.angular);
}
})(function($, angular) {
(function ($) {
function patch(obj, fnName, callback) {
var _old = obj[fnName];
obj[fnName] = function () {
return callback(_old, this, arguments);
}
}
// patch for selectmenu when it opens a menu in an own page
$( document ).bind( "selectmenubeforecreate", function( event ) {
var selectmenuWidget = $( event.target ).data( "selectmenu" );
patch(selectmenuWidget, 'close', function (old, self, args) {
if (self.options.disabled || !self.isOpen) {
return;
}
if (self.menuType === "page") {
// See mobile.dialog#close for the same logic as here!
var dst = $.mobile.urlHistory.getPrev().url;
if (!$.mobile.path.isPath(dst)) {
dst = $.mobile.path.makeUrlAbsolute("#" + dst);
}
$.mobile.changePage(dst, { changeHash:false, fromHashChange:true });
self.isOpen = false;
} else {
old.apply(self, args);
}
});
});
// selectmenu may create parent elements and extra pages
patch($.mobile.selectmenu.prototype, 'destroy', function (old, self, args) {
old.apply(self, args);
var menuPage = self.menuPage;
var screen = self.screen;
var listbox = self.listbox;
menuPage && menuPage.remove();
screen && screen.remove();
listbox && listbox.remove();
});
// native selectmenu throws an error is no option is contained!
$.mobile.selectmenu.prototype.placeholder = "";
// Listview may create subpages that need to be removed when the widget is destroyed.
patch($.mobile.listview.prototype, "destroy", function (old, self, args) {
// Destroy the widget instance first to prevent
// a stack overflow.
// Note: If there are more than 1 listview on the page, childPages will return
// the child pages of all listviews.
var id = self.element.attr('id');
var childPageRegex = new RegExp($.mobile.subPageUrlKey + "=" + id + "-");
var childPages = self.childPages();
old.apply(self, args);
for (var i = 0; i < childPages.length; i++) {
var childPage = $(childPages[i]);
var dataUrl = childPage.attr('data-url');
if (dataUrl.match(childPageRegex)) {
childPage.remove();
}
}
});
// refresh of listview should refresh also non visible entries if the
// listview itself is not visible
patch($.mobile.listview.prototype, "refresh", function (old, self, args) {
if (self.element.filter(":visible").length === 0) {
return old.call(self, true);
} else {
return old.apply(self, args);
}
});
// Copy of the initialization code from jquery mobile for controlgroup.
// Needed in jqm 1.1, as we want to do a manual initialization.
// See the open task in jqm 1.1 for controlgroup.
if ($.fn.controlgroup) {
$(document).bind("pagecreate create", function (e) {
$(":jqmData(role='controlgroup')", e.target)
.jqmEnhanceable()
.controlgroup({ excludeInvisible:false });
});
}
// Patch 1: controlgroup should not exclude invisible children
// as long as it is not visible itself!
patch($.fn, "controlgroup", function (old, self, args) {
if (self.filter(":visible").length === 0) {
var options = args[0] || {};
options.excludeInvisible = false;
return old.call(self, options);
}
return old.apply(self, args);
});
// collapsible has problems when a collapsible is created with a nested collapsible,
// if the nested collapsible is created before the outside collapsible.
var _c = $.fn.collapsible;
var nestedContentClass = "ui-collapsible-content";
$.fn.collapsible = function () {
var nestedContent = this.find(".ui-collapsible-content");
nestedContent.removeClass(nestedContentClass);
try {
return _c.apply(this, arguments);
} finally {
nestedContent.addClass(nestedContentClass);
}
};
// navbar does not contain a refresh function, so we add it here.
patch($.mobile.navbar.prototype, '_create', function (old, self, args) {
var _find = $.fn.find;
var navbar = self.element;
var navbarBtns;
$.fn.find = function (selector) {
var res = _find.apply(this, arguments);
if (selector === 'a') {
navbar.data('$navbtns', res);
}
return res;
};
try {
return old.apply(self, args);
} finally {
$.fn.find = _find;
}
});
$.mobile.navbar.prototype.refresh = function () {
var $navbar = this.element;
var $navbtns = $navbar.data("$navbtns");
$navbtns.splice(0, $navbtns.length);
$.each($navbar.find("a"), function (key, value) {
$navbtns.push(value);
});
var iconpos = $navbtns.filter(":jqmData(icon)").length ?
this.options.iconpos : undefined;
var list = $navbar.find("ul");
var listEntries = list.children("li");
list.removeClass(function (index, css) {
return (css.match(/\bui-grid-\S+/g) || []).join(' ');
});
listEntries.removeClass(function (index, css) {
return (css.match(/\bui-block-\S+/g) || []).join(' ');
});
list.jqmEnhanceable().grid({ grid:this.options.grid });
$navbtns.buttonMarkup({
corners:false,
shadow:false,
inline:true,
iconpos:iconpos
});
};
})(window.jQuery);
/**
* Helper that introduces the concept of precompilation: Preprocess the dom before
* angular processes it.
* <p>
* Usage: Create a decorator or a factory for the $precompile service.
*/
(function ($, angular) {
var ng = angular.module('ng');
ng.factory("$precompile", function() {
return function(element) {
// This is empty and can be decorated using $provide.decorator.
return element;
}
});
ng.config(['$provide', function ($provide) {
$provide.decorator('$compile', ['$precompile', '$delegate', function ($precompile, $compile) {
return function () {
arguments[0] = $precompile(arguments[0]);
return $compile.apply(this, arguments);
}
}]);
}]);
function precompileHtmlString(html, $precompile) {
var $template = $('<div>' + html + '</div>');
$precompile($template.contents());
return $template.html();
}
ng.config(['$compileProvider', '$provide', function ($compileProvider, $provide) {
var directiveTemplateUrls = {};
// Hook into the registration of directives to:
// - preprocess template html
// - mark urls from templateUrls so we can preprocess it later in $http
var _directive = $compileProvider.directive;
$compileProvider.directive = function (name, factory) {
var newFactory = function ($precompile, $injector) {
var res = $injector.invoke(factory);
if (res.template) {
res.template = precompileHtmlString(res.template, $precompile);
} else if (res.templateUrl) {
directiveTemplateUrls[res.templateUrl] = true;
}
return res;
};
return _directive.call(this, name, ['$precompile', '$injector', newFactory]);
};
// preprocess $http results for templateUrls.
$provide.decorator('$http', ['$q', '$delegate', '$precompile', function ($q, $http, $precompile) {
var _get = $http.get;
$http.get = function (url) {
var res = _get.apply(this, arguments);
if (directiveTemplateUrls[url]) {
var _success = res.success;
res.success = function(callback) {
var newCallback = function() {
var content = arguments[0];
arguments[0] = precompileHtmlString(content, $precompile);
return callback.apply(this, arguments);
};
return _success(newCallback);
};
}
return res;
};
return $http;
}]);
}]);
})($, angular);
(function (angular) {
var ng = angular.module('ng');
ng.config(['$provide', function($provide) {
$provide.decorator('$rootScope', ['$delegate', function($rootScope) {
$rootScope.$disconnect = function() {
if (this.$root == this) return; // we can't disconnect the root node;
var parent = this.$parent;
this.$$disconnected = true;
// See Scope.$destroy
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
this.$$nextSibling = this.$$prevSibling = null;
};
$rootScope.$reconnect = function() {
if (this.$root == this) return; // we can't disconnect the root node;
var child = this;
if (!child.$$disconnected) {
return;
}
var parent = child.$parent;
child.$$disconnected = false;
// See Scope.$new for this logic...
child.$$prevSibling = parent.$$childTail;
if (parent.$$childHead) {
parent.$$childTail.$$nextSibling = child;
parent.$$childTail = child;
} else {
parent.$$childHead = parent.$$childTail = child;
}
};
return $rootScope;
}]);
}]);
})(angular);
(function (angular) {
var ng = angular.module('ng');
ng.config(['$provide', function ($provide) {
$provide.decorator('$rootScope', ['$delegate', function ($rootScope) {
var _apply = $rootScope.$apply;
$rootScope.$apply = function () {
if ($rootScope.$$phase) {
return $rootScope.$eval.apply(this, arguments);
}
return _apply.apply(this, arguments);
};
var _digest = $rootScope.$digest;
$rootScope.$digest = function () {
if ($rootScope.$$phase) {
return;
}
var res = _digest.apply(this, arguments);
};
return $rootScope;
}]);
}]);
})(angular);
(function ($, angular) {
// Only digest the $.mobile.activePage when rootScope.$digest is called.
var ng = angular.module('ng');
$.mobile.autoInitializePage = false;
var lastCreatedPages = [];
var jqmInitialized = false;
ng.config(['$provide', function ($provide) {
$provide.decorator('$rootScope', ['$delegate', function ($rootScope) {
var _$digest = $rootScope.$digest;
var lastActiveScope;
$rootScope.$digest = function () {
if (this === $rootScope) {
var p = $.mobile.activePage;
var activeScope = p && p.scope();
if (lastActiveScope && lastActiveScope !== activeScope) {
lastActiveScope.$disconnect();
}
lastActiveScope = activeScope;
if (activeScope) {
activeScope.$reconnect();
}
}
var res = _$digest.apply(this, arguments);
if (this === $rootScope) {
var hasPages = lastCreatedPages.length;
while (lastCreatedPages.length) {
var pageScope = lastCreatedPages.shift();
// Detach the scope of the created pages from the normal $digest cycle.
// Needed so that only $.mobile.activePage gets digested when rootScope.$digest
// is called.
// However, allow one digest to process every page
// so that we can use ng-repeat also for jqm pages!
pageScope.$disconnect();
}
if (hasPages && !jqmInitialized) {
jqmInitialized = true;
var _changePage = $.mobile.changePage;
$.mobile.changePage = function () {};
//$.mobile.changePage.defaults = _changePage.defaults;
try {
$.mobile.initializePage();
} finally {
$.mobile.changePage = _changePage;
}
$rootScope.$broadcast("jqmInit");
}
}
return res;
};
return $rootScope;
}]);
}]);
function connectToDocument(node, callback) {
if (!node.parentNode) {
return callback();
}
// search the top most element for node.
while (node.parentNode && node.parentNode.nodeType === 1) {
node = node.parentNode;
}
var oldParentNode = node.parentNode;
if (oldParentNode !== document) {
document.documentElement.appendChild(node);
}
try {
return callback();
} finally {
if (oldParentNode !== document) {
oldParentNode.appendChild(node);
}
}
}
/**
* This directive will enhance the dom during compile
* with non widget markup. This will also mark elements that contain
* jqm widgets.
*/
ng.factory('$precompile', function () {
var pageSelector = ':jqmData(role="page"), :jqmData(role="dialog")';
return function (element) {
// save the old parent
var oldParentNode = element[0].parentNode;
// if the element is not connected with the document element,
// the enhancements of jquery mobile do not work (uses event listeners for the document).
// So temporarily connect it...
connectToDocument(element[0], function () {
var pages = element.find(pageSelector).add(element.filter(pageSelector));
pages.attr("ngm-page", "true");
// enhance non-widgets markup.
markJqmWidgetCreation(function () {
preventJqmWidgetCreation(function () {
if (pages.length > 0) {
// element contains pages.
// create temporary pages for the non widget markup, that we destroy afterwards.
// This is ok as non widget markup does not hold state, i.e. no permanent reference to the page.
pages.page();
} else {
element.parent().trigger("create");
}
});
});
// Destroy the temporary pages again
pages.page("destroy");
});
// If the element wrapped itself into a new element,
// return the element that is under the same original parent
while (element[0].parentNode !== oldParentNode) {
element = element.eq(0).parent();
}
return element;
}
});
/**
* Special directive for pages, as they need an own scope.
*/
ng.directive('ngmPage', function () {
return {
restrict:'A',
scope:true,
compile:function (tElement, tAttrs) {
tElement.removeAttr("ngm-page");
return {
pre:function (scope, iElement, iAttrs) {
if (!$.mobile.pageContainer) {
$.mobile.pageContainer = iElement.parent().addClass("ui-mobile-viewport");
}
// Create the page widget without the pagecreate-Event.
// This does no dom transformation, so it's safe to call this in the prelink function.
createPagesWithoutPageCreateEvent(iElement);
lastCreatedPages.push(scope);
iElement.bind('pagebeforeshow', function (event) {
var page = $(event.target);
scope.$emit("jqmPagebeforeshow", page);
scope.$root.$digest();
});
}
};
}
};
});
// If jqm loads a page from an external source, angular needs to compile it too!
ng.run(['$rootScope', '$compile', function ($rootScope, $compile) {
patchJq('page', function () {
if (!preventJqmWidgetCreation() && !this.data("page")) {
if (this.attr("data-" + $.mobile.ns + "external-page")) {
correctRelativeLinks(this);
$compile(this)($rootScope);
}
}
return $.fn.orig.page.apply(this, arguments);
});
var base = $.mobile.base.element.attr("href");
function correctRelativeLinks(page) {
// correct the relative links in this page relative
// to the page url.
// Jqm does this when a link is clicked (using link.attr("href"),
// but we want to use link.prop("href")
var url = page.jqmData( "url" );
if ( !url || !$.mobile.path.isPath( url ) ) {
url = base;
}
var pageUrl = $.mobile.path.makeUrlAbsolute( url, base);
page.find( "a:not([rel='external'], [target])" ).each(function() {
var $this = $(this),
thisUrl = $this.attr( 'href' );
$this.attr('href', $.mobile.path.makeUrlAbsolute(thisUrl, pageUrl));
});
}
}]);
$.mobile.registerJqmNgWidget = function (widgetName, widgetSpec) {
jqmWidgets[widgetName] = widgetSpec;
patchJqmWidget(widgetName, widgetSpec.precompile);
};
var jqmWidgets = {};
/**
* Directive for calling the create function of a jqm widget.
* For elements that wrap themselves into new elements (like `<input type="checked">`) ngmCreate will be called
* on the wrapper element for the input and the label, which is created during precompile.
* ngmLink will be called on the actual input element, so we have access to the ngModel and attrs for $observe calls.
*/
ng.directive("ngmCreate", function () {
return {
restrict:'A',
// after the normal angular widgets like input, ngModel, ...
priority:0,
compile:function (tElement, tAttrs) {
var widgets = JSON.parse(tAttrs.ngmCreate);
return {
post:function (scope, iElement, iAttrs, ctrls) {
var widgetName, widgetSpec, initArgs, origCreate;
for (widgetName in widgets) {
widgetSpec = jqmWidgets[widgetName];
initArgs = widgets[widgetName];
origCreate = $.fn.orig[widgetName];
if (widgetSpec.create) {
widgetSpec.create(origCreate, iElement, initArgs);
} else {
origCreate.apply(iElement, initArgs);
}
}
}
};
}
}
});
/**
* Directive for connecting widgets with angular. See ngmCreate.
*/
ng.directive("ngmLink", ["$injector", function ($injector) {
return {
restrict:'A',
priority:0,
require:['?ngModel'],
compile:function (tElement, tAttrs) {
var widgets = JSON.parse(tAttrs.ngmLink);
return {
post:function (scope, iElement, iAttrs, ctrls) {
var widgetName, widgetSpec;
for (widgetName in widgets) {
widgetSpec = jqmWidgets[widgetName];
widgetSpec.link(scope, iElement, iAttrs, ctrls, $injector);
}
}
};
}
}
}]);
function patchJqmWidget(widgetName, precompileFn) {
patchJq(widgetName, function () {
if (markJqmWidgetCreation()) {
var args = Array.prototype.slice.call(arguments);
var self = this;
for (var k = 0; k < self.length; k++) {
var element = self.eq(k);
var createElement = element;
if (precompileFn) {
createElement = precompileFn(element, args) || createElement;
}
var ngmCreateStr = createElement.attr("ngm-create") || '{}';
var ngmCreate = JSON.parse(ngmCreateStr);
ngmCreate[widgetName] = args;
createElement.attr("ngm-create", JSON.stringify(ngmCreate));
// attribute needs to be after the ngm-create attribute!
var ngmLinkStr = element.attr("ngm-link") || '{}';
var ngmLink = JSON.parse(ngmLinkStr);
ngmLink[widgetName] = true;
element.attr("ngm-link", JSON.stringify(ngmLink));
}
}
if (preventJqmWidgetCreation()) {
return false;
}
return $.fn.orig[widgetName].apply(this, arguments);
});
}
$.fn.orig = {};
function patchJq(fnName, callback) {
$.fn.orig[fnName] = $.fn.orig[fnName] || $.fn[fnName];
$.fn[fnName] = callback;
}
var _execFlags = {};
function execWithFlag(flag, fn) {
if (!fn) {
return _execFlags[flag];
}
var old = _execFlags[flag];
_execFlags[flag] = true;
var res = fn();
_execFlags[flag] = old;
return res;
}
function preventJqmWidgetCreation(fn) {
return execWithFlag('preventJqmWidgetCreation', fn);
}
function markJqmWidgetCreation(fn) {
return execWithFlag('markJqmWidgetCreation', fn);
}
function createPagesWithoutPageCreateEvent(pages) {
preventJqmWidgetCreation(function () {
var oldPrefix = $.mobile.page.prototype.widgetEventPrefix;
$.mobile.page.prototype.widgetEventPrefix = 'noop';
pages.page();
$.mobile.page.prototype.widgetEventPrefix = oldPrefix;
});
}
})($, angular);
(function (angular, $) {
var widgetConfig = {
checkboxradio:{
handlers:[disabledHandler, refreshAfterNgModelRender, checkedHandler],
precompile:checkboxRadioPrecompile,
create:checkboxRadioCreate
},
// Button wraps itself into a new element.
// Angular does not like this, so we do it in advance.
button:{
handlers:[disabledHandler],
precompile:buttonPrecompile,
create:buttonCreate
},
collapsible:{
handlers:[disabledHandler, collapsedHandler]
},
textinput:{
handlers:[disabledHandler],
precompile:textinputPrecompile,
create:unwrapFromDivCreate
},
slider:{
handlers:[disabledHandler, refreshAfterNgModelRender],
precompile:wrapIntoDivPrecompile,
create:sliderCreate
},
listview:{
handlers:[refreshOnChildrenChange]
},
collapsibleset:{
handlers:[refreshOnChildrenChange]
},
// selectmenu wraps itself into a button and an outer div.
// Angular does not like this, so we do it in advance.
selectmenu:{
handlers:[disabledHandler, refreshAfterNgModelRender, refreshOnChildrenChange],
precompile:wrapIntoDivPrecompile,
create:unwrapFromDivCreate
},
controlgroup:{
handlers:[refreshControlgroupOnChildrenChange]
},
navbar:{
handlers:[refreshOnChildrenChange]
},
dialog:{
handlers:[],
precompile:dialogPrecompile,
create:dialogCreate
},
fixedtoolbar:{
handlers:[]
},
popup:{
handlers:[]
}
};
function mergeHandlers(widgetName, list) {
return function ($injector) {
var args = Array.prototype.slice.call(arguments);
args.unshift(widgetName);
args.push($injector);
for (var i = 0; i < list.length; i++) {
list[i].apply(this, args);
}
}
}
var config;
for (var widgetName in widgetConfig) {
config = widgetConfig[widgetName];
config.link = mergeHandlers(widgetName, config.handlers);
$.mobile.registerJqmNgWidget(widgetName, config);
}
// -------------------
// precompile and create functions
// Slider appends a new element after the input/select element for which it was created.
// The angular compiler does not like this, so we wrap the two elements into a new parent node.
function sliderCreate(origCreate, element, initArgs) {
// This is important, as the contained div als uses inline-block!
element[0].style.display = 'inline-block';
var slider = element.children().eq(0);
origCreate.apply(slider, initArgs);
}
// Checkboxradio requires a label for every checkbox input and wraps itself as well as the label
// into that div. Angular does not like those changes in the DOM, so we do it in advance.
function checkboxRadioPrecompile(origElement, initArgs) {
// See the checkboxradio-Plugin in jqm for the selectors used to locate the label.
var parentLabel = $(origElement).closest("label");
var container = $(origElement).closest("form,fieldset,:jqmData(role='page'),:jqmData(role='dialog')");
if (container.length === 0) {
container = origElement.parent();
}
var label = parentLabel.length ? parentLabel : container.find("label").filter("[for='" + origElement[0].id + "']");
if (label.length===0) {
origElement.attr("ng-non-bindable", "true");
} else {
var wrapper = wrapIntoDivPrecompile(label);
moveCloningDirectives(origElement, wrapper);
wrapper.append(origElement);
return wrapper;
}
}
function checkboxRadioCreate(origCreate, element, initArgs) {
// wrap the input into it's label. By this, the jqm widget will always
// use this label, even if there are other labels with the same id on the same page.
// This is important if we use ng-repeat on checkboxes, as this could
// create multiple checkboxes with the same id!
var label = element.children("label");
var input = element.children("input");
label.append(input);
return unwrapFromDivCreate(function() {
return origCreate.apply(input, arguments);
}, element, initArgs);
}
function buttonPrecompile(origElement, initArgs) {
var wrapper = wrapIntoDivPrecompile(origElement);
// Add a text node with the value content,
// so that angular bindings work for the value too
if (origElement[0].nodeName === 'INPUT') {
var value = origElement.val();
origElement.append(document.createTextNode(value));
}
return wrapper;
}
function buttonCreate(origCreate, element, initArgs) {
// Button destroys the text node and recreates a new one. This does not work
// if the text node contains angular expressions, so we move the
// text node to the right place.
var button = element.children().eq(0);
var textNode = button.contents();
var res = unwrapFromDivCreate(origCreate, element, initArgs);
var textSpan = element.find(".ui-btn-text");
textSpan.empty();
textSpan.append(textNode);
return res;
}
// textinput for input-type "search" wraps itself into a new element
function textinputPrecompile(origElement, initArgs) {
if (!origElement.is("[type='search'],:jqmData(type='search')")) {
return origElement;
}
return wrapIntoDivPrecompile(origElement);
}
function wrapIntoDivPrecompile(origElement) {
origElement.wrapAll("<div></div>");
var wrapper = origElement.parent();
moveCloningDirectives(origElement, wrapper);
return wrapper;
}
function unwrapFromDivCreate(origCreate, element, initArgs) {
if (element[0].nodeName.toUpperCase() !== "DIV") {
// no wrapper existing.
return origCreate.apply(element, initArgs);
}
if (isMock(origCreate)) {
// spy that does not call through
return origCreate.apply(element, initArgs);
}
var child = element.children().eq(0);
child.insertBefore(element);
element.empty();
return useExistingElementsForNewElements(element, function () {
return origCreate.apply(child, initArgs);
});
}
// Dialog: separate event binding and dom enhancement.
// Note: We do need to add the close button during precompile,
// as the enhancement for the dialog header depends on it (calculation which button is left, right, ...)
// We cannot adjust the timing of the header enhancement as it is no jqm widget.
function dialogPrecompile(origElement, initAttrs) {
var options = $.mobile.dialog.prototype.options;
var headerCloseButton = $("<a href='#' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>" + options.closeBtnText + "</a>");
origElement.find(":jqmData(role='header')").prepend(headerCloseButton);
origElement.data('headerCloseButton', headerCloseButton);
return origElement;
}
function dialogCreate(origCreate, element, initArgs) {
if (isMock(origCreate)) {
// During unit tests...
return origCreate.apply(element, initArgs);
}
var headerCloseButton = element.data('headerCloseButton');
return useExistingElementsForNewElements(headerCloseButton, function () {
return origCreate.apply(element, initArgs);
});
}
function isMock(origCreate) {
return origCreate.isSpy && origCreate.originalValue !== origCreate.plan;
}
function useExistingElementsForNewElements(existingElements, callback) {
var i, el, tagName;
var existingElementsHashByElementName = {};
for (i = 0; i < existingElements.length; i++) {
el = existingElements.eq(i);
// Do not use jQuery.fn.remove as this will fire a destroy event,
// which leads to unwanted side effects by it's listeners.
el[0].parentNode.removeChild(el[0]);
tagName = el[0].nodeName.toUpperCase();
existingElementsHashByElementName[tagName] = el;
}
function useExistingElementIfPossible(selector) {
if (selector) {
var template = $(selector);
var tagName = template[0].nodeName.toUpperCase();
var existingElement = existingElementsHashByElementName[tagName];
if (existingElement) {
delete existingElementsHashByElementName[tagName];
existingElement[0].className += ' ' + template[0].className;
return existingElement;
}
}
return false;
}
var res = withPatches($.fn, {
init:function (_init, self, args) {
var selector = args[0];
if (typeof selector === "string" && selector.charAt(0) === '<') {
var existingElement = useExistingElementIfPossible(selector);
if (existingElement) {
return existingElement;
}
}
return _init.apply(self, args);
},
wrap:function (_wrap, self, args) {
var selector = args[0];
var wrapper = useExistingElementIfPossible(selector);
if (wrapper) {
wrapper.insertBefore(self);
wrapper.append(self);
return self;
}
return _wrap.apply(self, args);
},
wrapAll:function (_wrapAll, self, args) {
var selector = args[0];
var wrapper = useExistingElementIfPossible(selector);
if (wrapper) {
wrapper.insertBefore(self);
wrapper.append(self);
return self;
}
return _wrapAll.apply(self, args);
}
}, callback);
for (tagName in existingElementsHashByElementName) {
throw new Error("existing element with tagName " + tagName + " was not used!");
}
return res;
}
function withPatches(obj, patches, callback) {
var _old = {};
var executingCount = 0;
function patchProp(prop) {
var oldFn = _old[prop] = obj[prop];
oldFn.restore = function () {
obj[prop] = oldFn;
delete oldFn.restore;
};
obj[prop] = function () {
if (executingCount) {
return oldFn.apply(this, arguments);
}
executingCount++;
try {
return patches[prop](oldFn, this, arguments);
} finally {
executingCount--;
}
};
obj[prop].prototype = oldFn.prototype;
}
var prop;
for (prop in patches) {
patchProp(prop);
}
try {
return callback();
} finally {
for (prop in _old) {
_old[prop].restore && _old[prop].restore();
}
}
}
var CLONING_DIRECTIVE_REGEXP = /(^|[\W])(repeat|switch-when|if)($|[\W])/;
function moveCloningDirectives(source, target) {
// iterate over the attributes
var cloningAttrNames = [];
var node = source[0];
var targetNode = target[0];
var nAttrs = node.attributes;
var attrCount = nAttrs && nAttrs.length;
if (attrCount) {
for (var attr, name,
j = attrCount - 1; j >= 0; j--) {
attr = nAttrs[j];
name = attr.name;
if (CLONING_DIRECTIVE_REGEXP.test(name)) {
node.removeAttributeNode(attr);
targetNode.setAttributeNode(attr);
}
}
}
// iterate over the class names.
var targetClassName = '';
var className = node.className;
var match;
if (className) {
className = className.replace(/[^;]+;?/, function (match) {
if (CLONING_DIRECTIVE_REGEXP.test(match)) {
targetClassName += match;
return '';
}
return match;
});
}
if (targetClassName) {
targetNode.className = targetClassName;
node.className = className;
}
}
// Expose for tests.
$.mobile.moveCloningDirectives = moveCloningDirectives;
// -------------------
// link handlers
function disabledHandler(widgetName, scope, iElement, iAttrs, ctrls) {
iAttrs.$observe("disabled", function (value) {
if (value) {
iElement[widgetName]("disable");
} else {
iElement[widgetName]("enable");
}
});
}
function collapsedHandler(widgetName, scope, iElement, iAttrs, ctrls, $inject) {
var $parse = $inject.get("$parse");
if (iAttrs.collapsed) {
var collapsedGetter = $parse(iAttrs.collapsed);
var collapsedSetter = collapsedGetter.assign;
scope.$watch(collapsedGetter, function (value) {
if (value) {
iElement.trigger("collapse");
} else {
iElement.trigger("expand");
}
});
if (collapsedSetter) {
iElement.bind("collapse", function () {
scope.$apply(function () {