-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathjquery.mobile.iscrollview.js
More file actions
1860 lines (1617 loc) · 78.6 KB
/
Copy pathjquery.mobile.iscrollview.js
File metadata and controls
1860 lines (1617 loc) · 78.6 KB
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
/******************************************************************************
jslint directives. In case you hate yourself, and need that reinforced...
You will still get a few warnings that can't be turned off, or that I'm just
too stubborn to "fix"
sloppy, white: let me indent any way I damn please! I like to line things
up nice and purty.
nomen: tolerate leading _ for variable names. Leading _ is a requirement for
JQuery Widget Factory private members
*******************************************************************************/
/*jslint browser: true, sloppy: true, white: true, nomen: true, regexp: true, todo: true,
maxerr: 50, indent: 2 */
/*global jQuery:false, iScroll:false, console:false, Event:false*/
/*******************************************************************************
But instead, be kind to yourself, and use jshint.
Note jshint nomen and white options are opposite of jslint
You can't specify an indent of you use white: false, otherwise it will
still complain
*******************************************************************************/
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true,
curly:true, browser:true, jquery:true, indent:2, maxerr:50, sloppy:true, white:false, nomen:false,
regexp:false, todo:true */
/*
jquery.mobile.iscrollview.js
Version: 1.2.5
jQuery Mobile iScroll4 view widget
Copyright (c), 2012 Watusiware Corporation
Distributed under the MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions: NO ADDITIONAl CONDITIONS.
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Derived in part from jquery.mobile.iscroll.js:
Portions Copyright (c) Kazuhiro Osawa
Dual licensed under the MIT or GPL Version 2 licenses.
Derived in part from (jQuery mobile) jQuery UI Widget-factory
plugin boilerplate (for 1.8/9+)
Author: @scottjehl
Further changes: @addyosmani
Licensed under the MIT license
dependency: iScroll 4.1.9 https://github.com/cubiq/iscroll or later (4.2 provided in demo)
jQuery 1.6.4 (JQM 1.0.1) or 1.7.1 (JQM 1.1) or 1.7.2 (JQM 1.2)
JQuery Mobile = 1.0.1 or 1.1 or 1.2-alpha1
*/
; // Ignore jslint/jshint warning - for safety - terminate previous file if unterminated
(function ($, window, document, undefined) { /* Ignore islint warning on "undefined" */
"use strict";
//----------------------------------
// "class constants"
//----------------------------------
var HasTouch = document.ontouchend !== undefined,
IsWebkit = (/webkit/i).test(navigator.appVersion),
IsAndroid = (/android/gi).test(navigator.appVersion),
IsFirefox = (/firefox/i).test(navigator.userAgent),
IsTouchPad = (/hp-tablet/gi).test(navigator.appVersion),
IsIDevice = (/(iPhone|iPad|iPod).*AppleWebKit/).test(navigator.appVersion),
IsIPad = (/iPad.*AppleWebKit/).test(navigator.appVersion),
// IDevice running Mobile Safari - not embedded UIWebKit or Standalone (= saved to desktop)
IsMobileSafari = (/(iPhone|iPad|iPod).*AppleWebKit.*Safari/).test(navigator.appVersion),
// IDevice native app using embedded UIWebView
IsUIWebView = (/(iPhone|iPad|iPod).*AppleWebKit.(?!.*Safari)/).test(navigator.appVersion),
// Standalone is when running a website saved to the desktop (SpringBoard)
IsIDeviceStandalone = IsIDevice && (window.navigator.Standalone !== undefined),
// Kludgey way to seeing if we have JQM v1.0.x, since there apparently is no
// way to access the version number!
JQMIsV1_0 = $.mobile.ignoreContentEnabled === undefined,
nextPageID = 1; // Used to generate event namespaces
/* Placed here instead of anonymous functions to facilitate debugging.
No logging, because these events are too frequent */
function _pageTouchmoveFunc(e) {
e.preventDefault();
}
//===============================================================================
// This essentially subclasses iScroll. Originally, this was just so that we could
// inject an iscrollview variable at the time of construction (so that it is
// available from the refresh callback which is first called during construction).
// But now we override several iScroll methods, as well.
//===============================================================================
// See: www.golimojo.com/etc/js-subclass.html
function _subclass(constructor, superConstructor) {
function SurrogateConstructor() {}
SurrogateConstructor.prototype = superConstructor.prototype;
var prototypeObject = new SurrogateConstructor();
prototypeObject.constructor = constructor;
constructor.prototype = prototypeObject;
}
function IScroll(iscrollview, scroller, options) {
// We need to add an iscrollview member to iScroll, so that we can efficiently
// pass the iscrollview when triggering jQuery events. Otherwise, we'd have to
// make a call to $(wrapper).jqmData() on each event trigger, which could have an impact
// on performance for high-frequency events.
this.iscrollview = iscrollview;
// The following functions are called from the proxy event functions. These are things
// we want to do in certain iScroll4 events.
// Emulate bottomOffset functionality in case iScroll doesn't have patch for bottomOffset
this._emulateBottomOffset = function(e) {
if (this.iscrollview.options.emulateBottomOffset) {
this.maxScrollY = this.wrapperH - this.scrollerH +
this.minScrollY + this.iscrollview.options.bottomOffset;
}
};
// Allow mouse clicks through to input elements
// Note that this is not an issue for touch devices, just mouse
this._fixInput = function(e) {
if (this.iscrollview.options.fixInput ) {
var tagName,
target = e.target;
while (target.nodeType !== 1) { target = target.parentNode; }
tagName = target.tagName.toLowerCase();
if (tagName === "select" || tagName === "input" || tagName === "textarea") {
return;
}
}
// If preventTouchHover, stop hover from occuring inside scroller for jQuery Mobile 1.0
// (Not used for 1.1)
if (this.iscrollview.options.preventTouchHover) { e.stopImmediatePropagation(); }
else { e.preventDefault(); }
};
// Perform an iScroll callback.
this._doCallback = function(callbackName, e, f) {
var v = this.iscrollview,
then = v._logCallback(callbackName, e);
if (f) { f.call(this, e); } // Perform passed function if present
v._trigger(callbackName.toLowerCase(), e, {"iscrollview": v}); // Then trigger widget event
v._logCallback(callbackName, e, then);
};
// Override _bind and _unbind functions in iScroll, so that we can monitor performance,
// gain control over events reaching/not reaching iScroll, and potentially use jQuery events
// instead of addEventListener().
//
// As of v1.2, using jQuery events is an experimental feature, and does not work in all
// scenarios. For example, jQuery 1.7.1 breaks mousewheel support. This feature is left in
// only to permit further experimentation.
//
// If using jQuery events, we ignore bubble (really, useCapture) parameter. Fortunately,
// iScroll never uses it.
//
// If using jQuery events, we substitute jQuery's mouseleave for mouseout, to prevent iScroll
// from getting a cascade of events when the mouse enters some inner element within the
// scroller. iScroll is only interested in the mouse leaving the scroller to the OUTSIDE.
// While iScroll doesn't spend much time in the callback if moving to an inner element,
// the cascade of events is annoying when monitoring performance with the debug option.
this._bind = function (type, el, bubble) {
var jqEvents = this.iscrollview.options.bindIscrollUsingJqueryEvents,
_type = jqEvents && type === "mouseout" ? "mouseleave" : type;
// Ignore attempt to bind to orientationchange or resize, since the widget handles that
if (type === "orientationchange" || type === "resize") {
this.iscrollview._logIscrollEvent("iScroll bind (ignored)", type);
return;
}
this.iscrollview._logIscrollEvent("iScroll bind", type);
if (jqEvents) { (el ? $(el) : this.iscrollview.$scroller).bind(_type, $.proxy(this.handleEvent, this)); }
else { (el || this.scroller).addEventListener(_type, this, !!bubble); }
};
this._unbind = function(type, el, bubble) {
var jqEvents = this.iscrollview.options.bindIscrollUsingJqueryEvents,
_type = jqEvents && type === "mouseout" ? "mouseleave" : type;
if (type === "orientationchange" || type === "resize") {
this.iscrollview._logIscrollEvent("iScroll unbind (ignored)");
return;
}
this.iscrollview._logIscrollEvent("iScroll unbind", type);
if (jqEvents) { $(el || this.iscrollview.$scroller).unbind(_type, this.handleEvent); }
else { (el || this.scroller).removeEventListener(_type, this, !!bubble); }
};
// Save a reference to the original handleEvent in iScroll. We'll need to call it from our
// override.
this._origHandleEvent = iScroll.prototype.handleEvent;
// Shim around iScroll.handleEvent, allows us to trace
this.handleEvent = function(e) {
var jqEvents = this.iscrollview.options.bindIscrollUsingJqueryEvents,
then;
then = this.iscrollview._logIscrollEvent("iScroll.handleEvent", e);
// If jQuery mouseleave, make iScroll think we are handling a mouseout event
if (jqEvents && e.type === "mouseleave") {
e.type = "mouseout";
this._origHandleEvent(e);
e.type = "mouseleave";
}
else { this._origHandleEvent(e); }
this.iscrollview._logIscrollEvent("iScroll.handleEvent", e, then);
};
// Override _resize function in iScroll, which calls refresh() and is only called on resize
// and orientationchange events. We call refresh() when necessary, so these are redundant.
// As well, some refreshes are deferred, and the user will need to refresh any jQuery Mobile
// widgets using a callbackBefore. So, it makes no sense to have iScroll do event-based
// refresh.
this._resize = function() { };
iScroll.call(this, scroller, options);
}
_subclass(IScroll, iScroll);
$.widget("mobile.iscrollview", $.mobile.widget, {
widgetEventPrefix: "iscroll_",
//=========================================================
// All instance variables are declared here. This is not
// strictly necessary, but is helpful to document the use
// of instance variables.
//=========================================================
iscroll: null, // The underlying iScroll object
$window: $(window),
$wrapper: [], // The wrapper element
$scroller: [], // The scroller element (first child of wrapper)
$scrollerContent: [], // Content of scroller, sandwitched between any pull-down/pull-up
$pullDown: [], // The pull-down element (if any)
$pullUp: [], // The pull-up element (if any)
$pullUpSpacer: [],
$page: [], // The page element that contains the wrapper
_wrapperHeightAdjustForBoxModel: 0, // This is set in _create
_firstScrollerExpand: true, // True on first scroller expand, so we can capture original CSS
createdAt: null, // Time when created - used as unique ID
pageID: null, // Each page that has 1 or more iscrollviews gets a unique page ID #
instanceID: null, // Each isntance of iscrollview created on a page gets a unique instance ID #
// True if this scroller content is "dirty" - i.e. needs refresh because refresh
// was deferred when the page was not the active page. This does NOT imply that the wrapper
// needs to be refreshed - see _sizeDirty, below.
_dirty: false,
_dirtyCallbackBefore: null,
_dirtyCallbackAfter: null,
_sizeDirty: false, // True if wrapper resize is needed because page size or fixed content
// size changed
//----------------------------------------------------
// Options to be used as defaults
//----------------------------------------------------
options: {
// iScroll4 options
// We only define those options here which have values that differ from
// iscroll4 defaults.
hScroll: false, // iScroll4 default is true
hScrollbar: false, // iScroll4 default is true
// Additional iScroll4 options will be back-filled from iscroll4
// iscrollview widget options
debug: false, // Enable some messages to console
// Debug true needed for any trace options
traceResizeWrapper: false, // Enable to trace resize wrapper
traceRefresh: false, // Enable to trace refresh
traceCreateDestroy: false, // Enable to trace create/destroy
traceIscrollEvents: false, // Enable to trace events handled by iScroll
tracedIscrollEvents: [], // List of specific iScroll events to trace, empty list for all
// Items are strings, like "touchstart"
traceWidgetEvents: false, // Enable to trace events registered by widget
// Note: in some cases we might bind to multiple events. You will have to include the multiple
// events in one string to filter on such a bind. For example, "resize orientationchange"
tracedWidgetEvents: [], // List of specific widget events to trace
traceIscrollCallbacks: false, // Enable to trace iScroll callbacks to the widget
tracedIscrollCallbacks: [], // List of specific iScroll callbacks to trace, empty list for all
// Items are strings, like "onRefresh"
traceWidgetCallbacks: false,
tracedWidgetCallbacks: [],
// bottomOffset is currently only in Watusi-patched iScroll. We emulate it in case it isn't
// there.
bottomOffset: 0,
emulateBottomOffset: true,
pageClass: "iscroll-page", // Class to be applied to pages containing this widget
wrapperClass: "iscroll-wrapper", // Class to be applied to wrapper containing this widget
scrollerClass: "iscroll-scroller", // Class to be applied to scroller within wrapper
pullDownClass: "iscroll-pulldown", // Class for pulldown element (if any)
pullUpClass: "iscroll-pullup", // Class for pullup element (if any)
pullLabelClass: "iscroll-pull-label", // Class for pull element label span
pullUpSpacerClass: "iscroll-pullup-spacer", // Class added to generated pullup spacer
scrollerContentClass: "iscroll-content", // Real content of scroller, not including pull-up, pull-down
fixedHeightClass: "iscroll-fixed", // Class applied to elements that match fixedHeightSelector
// The widget adds the fixedHeightClass to all elements that match fixedHeightSelector.
// Don't add the fixedHeightClass to elements manually. Use data-iscroll-fixed instead.
fixedHeightSelector: ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(iscroll-fixed)",
// true to resize the wrapper to take all viewport space after fixed-height elements
// (typically header/footer)
// false to not change the size of the wrapper
// For example, if using multiple iscrollview widgets on the same page, a maximum
// of one of them could resize to remaining space. You would need to explicitly
// set the height of additional iscrollviews and give them the fixed height class.
resizeWrapper: true,
// Space-separated list of events on which to resize/refresh iscroll4
// On some mobile devices you may wish to add/substitute orientationchange event
// iOS 4.x will trigger resize twice then orientationchange
// iOS 5.x will trigger resize once then orientationchange
// Android devices can trigger multiple events, but generally orientationchange before resize
// Devices are inconsistent as to when they first report the new width/height
// Android tends to first trigger orientationchange with the width/height unchanged, the
// orientationchange with the new width/height.
// Experimentation with other devices would be useful
resizeEvents: "resize" + ($.support.orientation ? " orientationchange" : ""),
// Refresh iscrollview on page show event. This should be true if content inside a
// scrollview might change while the page is cached but not shown, and application hasn't
// called refresh(), or deferRefresh is false.
refreshOnPageBeforeShow: false,
// true to fix iscroll4 input element focus problem in the widget.
// false if you are using a patched iscroll4 with different fix or to
// disable for some other reason
fixInput: true,
wrapperAdd: 0, // Shouldn't be necessary, but in case user needs to fudge
// Can be + or -
// Timeout to allow page to render prior to refresh()
refreshDelay: IsAndroid ? 200 : 0, // Wild-ass guesses
// true to set the minimum height of scroller content (not including
// any pull-down or pull-up) to the height of the wrapper. Note that
// if there is a pull-down or pull-up, then this is done regardless of
// this option, because you have to be able to scroll the empty content
// to access the pull-down or pull-up. Set this option false if you do
// not want to show a scrollbar on short content. However, this will have
// the side-effect of making the "empty" part of the scroller non-draggable.
// Leaving this true provides a more consistent UI behaviour.
scrollShortContent: true,
// Normally, we need the wrapper to have no padding. Otherwise, the result will look awkward,
// you won't be able to grab the padded area to scroll, etc.
removeWrapperPadding: true,
// But we want to add that padding back inside the scroller. We add a div around the content
// inside any pull-down/pull-up to replace the padding removed from the wrapper.
addScrollerPadding: true,
// On some platforms (iOS, for example) we need to scroll to top after orientation change,
// because the address bar pushed the window down. jQuery Mobile handles this for page links,
// but doesn't for orientationchange.
// If you have multiple scrollers, only enable this for one of them
scrollTopOnResize: true,
scrollTopOnOrientatationChange: true,
// iScroll scrolls the first child of the wrapper. I don't see a use case for having more
// than one child. What kind of mess is going to be shown in that case? So, by default, we
// just wrap ALL of the children of the wrapper with a new <div> that will be the scroller.
// This way you don't need to worry about wrapping all the elements to be scrolled if there
// is more than one. If there is only one child, we create this <div> unnecessarily, but -
// big deal. If, for some reason, you want to create the markup for the scroller yourself,
// set this to false.
createScroller: true,
// True to defer refresh() on non-active pages until pagebeforeshow. This avoids
// unnecessary refresh in case of resize/orientation change when pages are cached,
// as well as unnecessary refresh when pages are updated when they are not the active
// page.
deferNonActiveRefresh: true,
// Same deal, for re-sizing the wrapper
deferNonActiveResize: true,
// True to prevent hover in scroller touch devices. If this is false, you will get
// "piano keyboard" effect in JQM <1.1 when scrolling due to hover, which is both
// time-consuming and distracting. A negative is that with the current implementation, you will
// never get a "hover" visual effect within a scroller on touch devices, even when not scrolling.
// But you still will on desktop browser with mouse, and you will still get "down" effect
// when a link is selected. This really is a jQuery Mobile problem with listview, and is
// fixed in JQM 1.1.
preventTouchHover: JQMIsV1_0 && HasTouch, // Enable if touch device and JQM version is < 1.1
// This is an experimental feature under development and DOES NOT WORK completely!
// For one, it breaks mousewheel with jQuery Mobile 1.1 (because jQuery Mobile 1.1 breaks
// mousewheel...)
bindIscrollUsingJqueryEvents: false,
// If fastDestroy is true, don't tear down the widget on destroy. The assumption is destroy
// will only be called when the page is removed, so there is no need. Is anyone really
// going to un-enhance a scroller? If so, set this to false, but then you will have to
// fix the unbind issue...
fastDestroy: false,
// Prevent scrolling the page by grabbing areas outside of the scroller.
// Normally, this should be true. Set this false if you are NOT using a fixed-height page,
// but instead are using iScroll to scroll an area within a scollable page. If you have
// multiple scrollers on a scrollable page, then set this false for all of them.
// Note that we ALWAYS prevent scrolling the page by dragging inside the scroller.
preventPageScroll: true,
pullDownResetText : "Pull down to refresh...",
pullDownPulledText : "Release to refresh...",
pullDownLoadingText : "Loading...",
pullUpResetText : "Pull up to refresh...",
pullUpPulledText : "Release to refresh...",
pullUpLoadingText : "Loading...",
pullPulledClass : "iscroll-pull-pulled",
pullLoadingClass : "iscroll-pull-loading",
//-------------------------------------------------------------
// For better or worse, widgets have two mechanisms for dealing
// with events. The needs to be a set of options that correspond
// to each event. If present, the option is a function. As
// well, the widget prepends the widget event prefix ("iscroll_")
// to each event name and triggers a jQuery event by that name.
// BOTH mechanisms can be used simultaneously, though not sure
// why you'd want to. If you need to handle an event during
// iScroll4 instantiation, (only one I know about that might be
// called is refresh) then you have to use a function option.
//-------------------------------------------------------------
onrefresh: null,
onbeforescrollstart: null,
onscrollstart: null,
onbeforescrollmove: null,
onscrollmove: null,
onbeforescrollend: null,
onscrollend: null,
ontouchend: null,
ondestroy: null,
onzoomstart: null,
onzoom: null,
onzoomend: null,
onpulldownreset: null,
onpulldownpulled: null,
onpulldown: null,
onpullupreset: null,
onpulluppulled: null,
onpullup: null,
onbeforerefresh: null,
onafterrefresh: null
},
//---------------------------------------------------------------------------------------
// Array of keys of options that are widget-only options (not options in iscroll4 object)
//---------------------------------------------------------------------------------------
_widgetOnlyOptions: [
"debug",
"traceIscrollEvents",
"tracedIscrollEvents",
"traceIscrollCallbacks",
"tracedIscrollCallbacks",
"traceWidgetEvents",
"tracedWidgetEvents",
"traceWidgetCallbacks",
"tracedWidgetCallbacks",
"traceResizeWrapper",
"traceRefresh",
"traceCreateDestroy",
"bottomOffset",
"emulateBottomOffset",
"pageClass",
"wrapperClass",
"scrollerClass",
"pullDownClass",
"pullUpClass",
"scrollerContentClass",
"pullLabelClass",
"pullUpSpacerClass",
"fixedHeightSelector",
"resizeWrapper",
"resizeEvents",
"refreshOnPageBeforeShow",
"fixInput",
"wrapperAdd",
"refreshDelay",
"scrollShortContent",
"removeWrapperPadding",
"addScrollerPadding",
"createScroller",
"deferNonActiveRefresh",
"preventTouchHover",
"deferNonActiveResize",
"bindIscrollUsingJqueryEvents",
"scrollTopOnResize",
"scrollTopOnOrientationChange",
"pullDownResetText",
"pullDownPulledText",
"pullDownLoadingText",
"pullUpResetText",
"pullUpPulledText",
"pullUpLoadingText",
"pullPulledClass",
"pullLoadingClass",
"onpulldownreset",
"onpulldownpulled",
"onpulldown",
"onpullupreset",
"onpulluppulled",
"onpullup",
"onbeforerefresh",
"onafterrefresh",
"fastDestroy"
],
//-----------------------------------------------------------------------
// Map of widget event names to corresponding iscroll4 object event names
//-----------------------------------------------------------------------
_event_map: {
onrefresh: "onRefresh",
onbeforescrollstart: "onBeforeScrollStart",
onscrollstart: "onScrollStart",
onbeforescrollmove: "onBeforeScrollMove",
onscrollmove: 'onScrollMove',
onbeforescrollend: 'onBeforeScrollEnd',
onscrollend: "onScrollEnd",
ontouchend: "onTouchEnd",
ondestroy: "onDetroy",
onzoomstart: "onZoomStart",
onzoom: "onZoom",
onzoomend: "onZoomEnd"
},
//------------------------------------------------------------------------------
// Functions that adapt iscroll callbacks to Widget Factory conventions.
// These are copied to the iscroll object's options object on instantiation.
// They call the private _trigger method provided by the widget factory
// base object. Normally, iscroll4 callbacks can be null or omitted. But since
// we can't know in advance whether the corresponding widget events might be bound
// or delegated in the future, we have set a callback for each that calls _trigger.
// This will call the corresponding widget callback as well as trigger the
// corresponding widget event if bound.
//
// Event callbacks are passed two values:
//
// e The underlying DOM event (if any) associated with this event
// d Data map
// iscrollview : The iscrollview object
//------------------------------------------------------------------------------
_proxy_event_funcs: {
onRefresh: function(e) {
this._doCallback("onRefresh", e, function(e) {
this._emulateBottomOffset();
this.iscrollview._pullOnRefresh.call(this.iscrollview,e);
});
},
onBeforeScrollStart: function(e) {
this._doCallback("onBeforeScrollStart", e, function(e) {
this._fixInput(e);
});
},
onScrollStart: function(e) { this._doCallback("onScrollStart", e); },
onBeforeScrollMove: function(e) {
this._doCallback("onBeforeScrollMove", e);
e.preventDefault(); // Don't scroll the page for touchmove inside scroller
},
onScrollMove: function(e) {
this._doCallback("onScrollMove", e, function(e) {
this.iscrollview._pullOnScrollMove.call(this.iscrollview, e);
});
},
onBeforeScrollEnd: function(e) { this._doCallback("onBeforeScrollEnd", e); },
onScrollEnd: function(e) {
this._doCallback("onScrollEnd", e, function(e){
this.iscrollview._pullOnScrollEnd.call(this.iscrollview, e);
});
},
onTouchEnd: function(e) { this._doCallback("onTouchEnd", e); },
onDestroy: function(e) { this._doCallback("onDestroy", e); },
onZoomStart: function(e) { this._doCallback("onZoomStart", e); },
onZoom: function(e) { this._doCallback("onZoom", e); },
onZoomEnd: function(e) { this._doCallback("onZoomEnd", e); }
},
// Merge options from the iscroll object into the widget options
// So, this will backfill iscroll4 defaults that we don't set in
// the widget, giving a full set of iscroll options, and leaving
// widget-only options untouched.
_merge_from_iscroll_options: function() {
var options = $.extend(true, {}, this.iscroll.options);
// Delete event options from the temp options
$.each(this._proxy_event_funcs, function(k,v) {delete options[k];});
if (this.options.emulateBottomOffset) { delete options.bottomOffset; }
$.extend(this.options, options); // Merge result into widget options
},
// Create a set of iscroll4 object options from the widget options.
// We have to omit any widget-specific options that are
// not also iscroll4 options. Also, copy the proxy event functions to the
// iscroll4 options.
_create_iscroll_options: function() {
var options = $.extend(true, {}, this.options); // temporary copy of widget options
// Remove options that are widget-only options
$.each(this._widgetOnlyOptions, function(i,v) {delete options[v];});
// Remove widget event options
$.each(this._event_map, function(k,v) {delete options[k];});
if (this.options.emulateBottomOffset) { delete options.bottomOffset; }
// Add proxy event functions
return $.extend(options, this._proxy_event_funcs);
},
// Formats number with fixed digits
_pad: function(num, digits, padChar) {
var str = num.toString(),
_padChar = padChar || "0";
while (str.length < digits) { str = _padChar + str; }
return str;
},
// Format time for logging
_toTime: function(date) {
return this._pad(date.getHours(), 2) + ":" +
this._pad(date.getMinutes(), 2) + ":" +
this._pad(date.getSeconds(), 2) + "." +
this._pad(date.getMilliseconds(), 3);
},
// Log a message to console
// text - message to log
// now - optional timestamp, if missing generates new timestamp
// Returns timestamp
_log: function(text, now) {
var _now, id, idStr;
if (!this.options.debug) { return null; }
_now = now || new Date();
id = this.$wrapper.attr("id");
idStr = id ? "#" + id : "";
console.log(this._toTime(_now) + " " +
$.mobile.path.parseUrl(this.$page.jqmData("url")).filename + idStr + " " +
text );
return _now;
},
// Log elapsed time from then to now
_logInterval: function(text, then) {
var now;
if (!this.options.debug) { return null; }
now = new Date();
return this._log(text + " " + (now - then) + "mS from " + this._toTime(then), now );
},
// Log an event
// Like _logInterval, but additional optional parameter e
// If e is present, additionally show interval from original event to now
_logEvent: function(text, e, then) {
var now,
eventTime,
haveEvent = e && e instanceof Object,
type = haveEvent ? e.type : e,
_text = type + " " + text;
if (!this.options.debug) { return null; }
now = new Date();
if (then) {
_text += " end " + (+(now-then)) + "mS from " + this._toTime(then);
}
else if (haveEvent) {
_text += " begin";
}
if (haveEvent) {
eventTime = new Date(e.timeStamp);
_text += " (" + (now - eventTime) + "mS from " +e.type + " @ " + this._toTime(eventTime) + ")";
}
return this._log(_text, now);
},
// Log a callback issued by iScroll
_logCallback: function(callbackName, e, then) {
if (!this.options.debug ||
!this.options.traceIscrollCallbacks ||
(this.options.tracedIscrollCallbacks.length !== 0 &&
$.inArray(callbackName, this.options.tracedIscrollCallbacks) === -1) ) {
return null;
}
if (e) { return this._logEvent(callbackName, e, then); }
if (then) { return this._logInterval(callbackName + " end", then); }
return this._log(callbackName + " begin");
},
// Log an event handled by Iscroll
// e can be Event or event name
_logIscrollEvent: function(text, e, then) {
var haveEvent = e instanceof Event,
type = haveEvent ? e.type : e;
if (!this.options.debug ||
!this.options.traceIscrollEvents ||
(this.options.tracedIscrollEvents.length !== 0 &&
$.inArray(type, this.options.tracedIscrollEvents) === -1)) {
return null;
}
return this._logEvent(text, e, then);
},
// Log an event handled by the widget
_logWidgetEvent: function(text, e, then) {
var haveEvent = e instanceof Object,
type = haveEvent ? e.type : e;
if (!this.options.debug ||
!this.options.traceWidgetEvents ||
(this.options.tracedWidgetEvents.length !== 0 &&
$.inArray(type, this.options.tracedWidgetEvents) === -1)) {
return null;
}
return this._logEvent(text, e, then);
},
// Log a callback issued by the widtet
_logWidgetCallback: function(callbackName, e, then) {
if (!this.options.debug ||
!this.options.traceWidgetCallbacks ||
(this.options.tracedWidgetCallbacks.length !== 0 &&
$.inArray(callbackName, this.options.tracedWidgetCallbacks) === -1) ) {
return null;
}
if (e) { return this._logEvent(callbackName, e, then); }
if (then) { return this._logInterval(callbackName + " end", then); }
return this._log(callbackName + " begin");
},
// Log elapsed time from then to now and later to now
_logInterval2: function(text, then, later) {
var now;
if (!this.options.debug) { return; }
now = new Date();
this._log(text + " " +
(now - later) + "mS from " + this._toTime(later) +
" (" + (now - then) + "mS from " + this._toTime(then) + ")" );
},
_startTiming: function() {
if (!this.options.debug) { return null; }
return new Date();
},
// Returns the event namespace for the page containing this widget
_pageEventNamespace: function() {
return ".iscroll_" + this.pageID;
},
// Returns the event namespace for this widget
_instanceEventNamespace: function() {
return this._pageEventNamespace() + "_" + this.instanceID;
},
// Takes a space-separated list of event types, and appends the given namespace to each
_addEventsNamespace: function(types_in, namespace) {
var types = types_in.split(" ");
$.each(types, function(k,v) {types[k] += namespace;});
return types.join(" ");
},
// All bind/unbind done by the widget goes through here, to permit logging
// Note: this used to be called _bind, but starting with JQM 1.2, this is a naming conflict with
// the Widget Factory code in JQM
_isvBind: function(obj, types_in, func, objName) {
var types = this._addEventsNamespace(types_in, this._instanceEventNamespace());
this._logWidgetEvent("bind " + objName, types);
obj.bind(types, $.proxy(func, this));
},
_bindPage: function(types_in, func) {
var types = this._addEventsNamespace(types_in, this._pageEventNamespace());
this._logWidgetEvent("bind $page", types);
this.$page.bind(types, $.proxy(func, this));
},
_isvUnbind: function(obj, types_in, objName) {
var types = this._addEventsNamespace(types_in, this._instanceEventNamespace());
this._logWidgetEvent("unbind " + objName, types);
obj.unbind(types);
},
_unbindPage: function(types_in) {
var types = this._addEventsNamespace(types_in, this._instanceEventNamespace());
this._logWidgetEvent("unbind $page", types);
this.$page.unbind(types);
},
// Currently unused - just in case we need it
_delegate: function(obj, selector, type, func, objName) {
this._logWidgetEvent("delegate " + objName + " " + selector, type);
obj.delegate(selector, type, $.proxy(func, this));
},
_triggerWidget: function(type, e) {
var then = this._logWidgetCallback(type);
this._trigger(type, e, {"iscrollview":this});
this._logWidgetCallback(type, e, then);
},
//-------------------------------------------------------------------
// Returns status of dirty flag, indicating that refresh() was called
// while the page was not active, and refresh will be deferred until
// pagebeforeshow.
//-------------------------------------------------------------------
isDirty: function() {
return this._dirty;
},
//-----------------------------------------------------------------------------
// Restore an element's styles to original
// If the style was never modified by the widget, the value passed in
// originalStyle will be undefined.
//
//If there originally was no style attribute, but styles were added by the
// widget, the value passed in originalStyle will be null.
//
// If there originally was a style attribute, but the widget modified it
// (actually, set some CSS, which changes the style, the value is a string in
// originalStyle.
//-----------------------------------------------------------------------------
_restoreStyle: function($ele, originalStyle) {
if (originalStyle === undefined) { return; }
if (originalStyle === null) { $ele.removeAttr("style"); }
else { $ele.attr("style", originalStyle); }
},
//------------------------------------------------------------------------------
// Functions that we bind to. They are declared as named members rather than as
// inline closures so we can properly unbind them.
//------------------------------------------------------------------------------
_pageBeforeShowFunc: function(e) {
var then = this._logWidgetEvent("_pageBeforeShowFunc", e);
if (this._dirty) {
this.resizeWrapper();
this.refresh(null, this._dirtyCallbackBefore, this._dirtyCallbackAfter, true);
this._dirty = false;
this._dirtyCallbackBefore = null;
this._dirtyCallbackAfter = null;
}
else if (this.options.refreshOnPageBeforeShow || this._sizeDirty) {
this.refresh(null,$.proxy(this._resizeWrapper, this),null,true);
}
this._sizeDirty = false;
this._logWidgetEvent("_pageBeforeShowFunc", e, then);
},
// Called on resize events
// TODO: Detect if size is unchanged, and if so just ignore?
_windowResizeFunc: function(e) {
var then = this._logWidgetEvent("_windowResizeFunc", e);
// Defer if not active page
if (this.options.deferNonActiveResize && !(this.$page.is($.mobile.activePage))) {
this._sizeDirty = true;
if (this.options.traceResizeWrapper) { this._log("resizeWrapper() (deferred)"); }
}
else {
this.resizeWrapper();
this.refresh(null,null,null,true);
}
this._logWidgetEvent("_windowResizeFunc", e, then);
},
// On some platforms (iOS, for example) you need to scroll back to top after orientation change,
// because the address bar pushed the window down. jQuery Mobile handles this for page links,
// but doesn't for orientationchange
_orientationChangeFunc: function(e) {
var then = this._logWidgetEvent("_orientationChangeFunc", e);
if (this.options.scrollTopOnOrientationChange) {
$.mobile.silentScroll(0);
}
this._logWidgetEvent("_orientationChangeFunc", e, then);
},
// Called when jQuery Mobile updates content such that a reflow is needed. This happens
// on collapsible content, etc.
_updateLayoutFunc: function(e) {
this.refresh();
},
// Get or set the count of instances on the page containing the widget
// This increases or decreases depending on the number of iscrollview widgets currently
// instantiated on the page.
_instanceCount: function(count_in) {
var key = "iscroll-private",
count = 0,
data = this.$page.jqmData(key) || {};
if (count_in !== undefined) {
count = count_in;
data.instanceCount = count;
this.$page.jqmData(key, data);
}
else {
if (data.instanceCount !== undefined) {
count = data.instanceCount;
}
}
return count;
},
_nextInstanceID: function(id_in) {
var key = "iscroll-private",
id = 1,
data = this.$page.jqmData(key) || {};
if (id_in !== undefined) {
id = id_in;
data.nextInstanceID = id;
this.$page.jqmData(key, data);
}
else {
if (data.nextInstanceID !== undefined) {
id = data.nextInstanceID;
}
}
return id;
},
_pageID: function(id_in) {
var key = "iscroll-private",
id = 1,
data = this.$page.jqmData(key) || {};
if (id_in !== undefined) {
id = id_in;
data.pageID = id;
this.$page.jqmData(key, data);
}
else {
if (data.pageID !== undefined) {
id = data.pageID;
}
}
return id;
},
//--------------------------------------------------------------------------
// Adapt the page for this widget
//--------------------------------------------------------------------------
_adaptPage: function() {
var _this = this;
// Only adapt the page if this is the only iscrollview widget instantiated on the page
// If the count >1, then the page has already been adapted. When the count goes back
// to 0, the changes will be un-done
if (this._instanceCount() === 1) {
this.$page.addClass(this.options.pageClass);
this.$page.find(this.options.fixedHeightSelector).each(function() { // Iterate over headers/footers/etc.
$(this).addClass(_this.options.fixedHeightClass);
});
if (HasTouch && this.options.preventPageScroll) {
this._bindPage("touchmove", _pageTouchmoveFunc);
}
}
},
_undoAdaptPage: function() {
var _this = this;
if (this._instanceCount() === 1) {
this.$page.find(this.options.fixedHeightSelector).each(function() { // Iterate over headers/footers/etc.
$(this).removeClass(_this.options.fixedHeightClass);
});
this.$page.removeClass(this.options.pageClass);