-
Notifications
You must be signed in to change notification settings - Fork 0
/
infinite.js
133 lines (106 loc) · 2.35 KB
/
infinite.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
/**
* Module dependencies.
*/
var events = require("events")
, Emitter = require("emitter")
, bind = require("bind")
, throttle = require("throttle");
/**
* Expose `Infinite`.
*/
module.exports = Infinite;
/**
* Initialize a new lazy loading scrolling list.
*
* @param {Object} el The DOMElement to listen of for scroll events.
* @param {Function} loadCallback
* @param {Number} margin Number of pixels to pre-trigger load.
* @api public
*/
function Infinite(el, loadCallback, margin) {
if(!(this instanceof Infinite))
return new Infinite(el, loadCallback, margin);
this.el = el;
if(typeof loadCallback == "function")
this.on("load", bind(this.el, loadCallback));
this.margin = typeof margin == "number" ? margin : 0;
this.iteration = 0;
this.paused = false;
// listen on scroll event
this.bind(this.el);
}
// Inherit from Emitter
Emitter(Infinite.prototype);
/**
* Bind to a DOMElement.
*
* @param {Object} el
* @api public
*/
Infinite.prototype.bind = function(el) {
if(el) this.el = el;
this.unbind();
this.events = events(this.el, this);
if(this.el.scrollHeight > this.el.clientHeight) this.events.bind("scroll");
else this.events.bind("mousewheel");
this.resume();
};
/**
* Unbind from the DOMElement.
*
* @api public
*/
Infinite.prototype.unbind = function() {
this.pause();
if(this.events) this.events.unbind();
};
/**
* Handle a scroll event.
*
* @param {Object} event
* @api public
*/
Infinite.prototype.onscroll = function() {
if(!this.paused && this.el.scrollHeight <= this.el.scrollTop + this.el.clientHeight + this.margin)
this.load();
};
/**
* Handle a mousewheel event.
*
* @param {Object} event
* @api public
*/
Infinite.prototype.onmousewheel = function(e) {
if(!this.paused) {
if(e.wheelDelta > 0) this.load(-1);
else this.load(1);
}
};
/**
* Issue a debounced load.
*
* @api public
*/
Infinite.prototype.load = throttle(function(i) {
var i = typeof i == "number" ? i : 1;
this.iteration = this.iteration + i;
this.emit("load", this.iteration, i);
}, 100);
/**
* Pause emitting `load` events.
*
* @api public
*/
Infinite.prototype.pause = function() {
this.paused = true;
this.emit("pause");
};
/**
* Resume emitting `load` events.
*
* @api public
*/
Infinite.prototype.resume = function() {
this.paused = false;
this.emit("resume");
};