-
Notifications
You must be signed in to change notification settings - Fork 6
/
flickity-sync.js
118 lines (101 loc) · 2.56 KB
/
flickity-sync.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
/*!
* Flickity sync v2.0.0
* enable sync for Flickity
*/
( function( window, factory ) {
// universal module definition
if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
require('flickity'),
require('fizzy-ui-utils'),
);
} else {
// browser global
factory(
window.Flickity,
window.fizzyUIUtils,
);
}
}( typeof window != 'undefined' ? window : this, function factory( Flickity, utils ) {
// -------------------------- sync prototype -------------------------- //
// Flickity.defaults.sync = false;
Flickity.create.sync = function() {
this.syncers = {};
let syncOption = this.options.sync;
this.on( 'destroy', this.unsyncAll );
if ( !syncOption ) return;
// HACK do async, give time for other flickity to be initalized
setTimeout( () => {
this.sync( syncOption );
} );
};
let proto = Flickity.prototype;
/**
* sync
* @param {[Element, String]} elem
*/
proto.sync = function( elem ) {
elem = utils.getQueryElement( elem );
let companion = Flickity.data( elem );
if ( !companion ) return;
// two hearts, that beat as one
this._syncCompanion( companion );
companion._syncCompanion( this );
};
/**
* @param {Flickity} companion
*/
proto._syncCompanion = function( companion ) {
let _this = this;
function syncListener() {
let index = _this.selectedIndex;
// do not select if already selected, prevent infinite loop
if ( companion.selectedIndex !== index ) {
companion.select( index );
}
}
this.on( 'select', syncListener );
// keep track of all synced flickities
// hold on to listener to unsync
this.syncers[ companion.guid ] = {
flickity: companion,
listener: syncListener,
};
};
/**
* unsync
* @param {[Element, String]} elem
*/
proto.unsync = function( elem ) {
elem = utils.getQueryElement( elem );
let companion = Flickity.data( elem );
this._unsync( companion );
};
/**
* @param {Flickity} companion
*/
proto._unsync = function( companion ) {
if ( !companion ) return;
// I love you but I've chosen darkness
this._unsyncCompanion( companion );
companion._unsyncCompanion( this );
};
/**
* @param {Flickity} companion
*/
proto._unsyncCompanion = function( companion ) {
let id = companion.guid;
let syncer = this.syncers[ id ];
this.off( 'select', syncer.listener );
delete this.syncers[ id ];
};
proto.unsyncAll = function() {
for ( let id in this.syncers ) {
let syncer = this.syncers[ id ];
this._unsync( syncer.flickity );
}
};
// ----- ----- //
return Flickity;
} ) );