Add clearEvents method & refactor setEvents

`clearEvents` helps write the tests and also gives
users the opportunity to remove all of this
functionality.

Refactor of `setEvents` tidies up use of `self`.
This commit is contained in:
Tom Byers
2019-07-22 14:11:43 +01:00
parent 9ef093cfda
commit 823c5a6119

View File

@@ -710,21 +710,36 @@
this.recalculate(); this.recalculate();
}; };
Sticky.prototype.setEvents = function () { Sticky.prototype.setEvents = function () {
var self = this; this._scrollEvent = this.onScroll.bind(this);
this._resizeEvent = this.onResize.bind(this);
// flag when scrolling takes place and check (and re-position) sticky elements relative to // flag when scrolling takes place and check (and re-position) sticky elements relative to
// window position // window position
if (self._scrollTimeout === false) { if (this._scrollTimeout === false) {
$(global).scroll(function (e) { self.onScroll(); }); $(global).scroll(this._scrollEvent);
self._scrollTimeout = global.setInterval(function (e) { self.checkScroll(); }, 50); this._scrollTimeout = global.setInterval(this.checkScroll.bind(this), 50);
} }
// Recalculate all dimensions when the window resizes // Recalculate all dimensions when the window resizes
if (self._resizeTimeout === false) { if (this._resizeTimeout === false) {
$(global).resize(function (e) { self.onResize(); }); $(global).resize(this._resizeEvent);
self._resizeTimeout = global.setInterval(function (e) { self.checkResize(); }, 50); this._resizeTimeout = global.setInterval(this.checkResize.bind(this), 50);
} }
}; };
Sticky.prototype.clearEvents = function () {
if (this._scrollTimeout !== false) {
$(global).off('scroll', this._scrollEvent);
global.clearInterval(this._scrollTimeout);
this._scrollTimeout = false;
}
if (this._resizeTimeout !== false) {
$(global).off('resize', this._resizeEvent);
global.clearInterval(this._resizeTimeout);
this._resizeTimeout = false;
}
};
Sticky.prototype.viewportIsWideEnough = function (windowWidth) { Sticky.prototype.viewportIsWideEnough = function (windowWidth) {
return windowWidth > 768; return windowWidth > 768;
}; };