-
Notifications
You must be signed in to change notification settings - Fork 21
/
jquery.event.frame.js
106 lines (91 loc) · 2.7 KB
/
jquery.event.frame.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
// jquery.events.frame.js
// 1.1 - lite
// Stephen Band
//
// Project home:
// webdev.stephband.info/events/frame/
//
// Source:
// http://github.com/stephband/jquery.event.frame
(function(jQuery, undefined){
var timer;
// Timer constructor
// fn - callback to call on each frame, with context set to the timer object
// fd - frame duration in milliseconds
function Timer( fn, fd ) {
var self = this,
clock;
function update(){
self.frameCount++;
fn.call(self);
}
this.frameDuration = fd || 25 ;
this.frameCount = -1 ;
this.start = function(){
update();
clock = setInterval(update, this.frameDuration);
};
this.stop = function(){
clearInterval( clock );
clock = null;
};
}
// callHandler() is the callback given to the timer object,
// it makes the event object and calls the handler
// context is the timer object
function callHandler(){
var fn = jQuery.event.special.frame.handler,
event = jQuery.Event("frame"),
array = this.array,
l = array.length;
// Give event object properties
event.frameCount = this.frameCount;
// Call handler on each elem in array
while (l--) {
fn.call(array[l], event);
}
}
if (!jQuery.event.special.frame) {
jQuery.event.special.frame = {
// Fires the first time an event is bound per element
setup: function(data, namespaces) {
if ( timer ) {
timer.array.push(this);
}
else {
timer = new Timer( callHandler, data && data.frameDuration );
timer.array = [this];
// Queue timer to start as soon as this thread has finished
var t = setTimeout(function(){
timer.start();
clearTimeout(t);
t = null;
}, 0);
}
return;
},
// Fires last time event is unbound per element
teardown: function(namespaces) {
var array = timer.array,
l = array.length;
// Remove element from list
while (l--) {
if (array[l] === this) {
array.splice(l, 1);
break;
}
}
// Stop and remove timer when no elems left
if (array.length === 0) {
timer.stop();
timer = undefined;
}
return;
},
handler: function(event){
// let jQuery handle the calling of event handlers
jQuery.event.handle.apply(this, arguments);
}
};
}
})(jQuery);