-
Notifications
You must be signed in to change notification settings - Fork 0
/
LatestEvent.scala
74 lines (67 loc) · 2.22 KB
/
LatestEvent.scala
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
package com.thoughtworks.binding
import com.thoughtworks.binding.Binding.{ChangedEvent, ChangedListener}
import org.scalajs.dom.raw._
import scala.scalajs.js
import scala.scalajs.js.|
/**
* @author 杨博 (Yang Bo)
*/
class LatestEvent[E <: Event](eventTarget: EventTarget, eventType: String) extends Binding[Option[E]] {
private var cache: Option[E] = None
private val publisher = new SafeBuffer[ChangedListener[Option[E]]]
protected def removeChangedListener(listener: ChangedListener[Option[E]]): Unit = {
publisher -= listener
if (publisher.isEmpty) {
eventTarget.removeEventListener(eventType, eventListener)
}
}
private val eventListener: js.Function1[E, _] = { upstreamEvent: E =>
cache = Some(upstreamEvent)
val changedEvent = new ChangedEvent(this, cache)
for (listener <- publisher) {
listener.changed(changedEvent)
}
}
protected def addChangedListener(listener: ChangedListener[Option[E]]): Unit = {
if (publisher.isEmpty) {
eventTarget.addEventListener(eventType, eventListener)
}
publisher += listener
}
protected def value: Option[E] = cache
}
object LatestEvent {
def hashchange(eventTarget: EventTarget) = {
new LatestEvent[Event](eventTarget, "hashchange")
}
def toggle(eventTarget: EventTarget) = {
new LatestEvent[Event](eventTarget, "toggle")
}
def input(eventTarget: EventTarget) = {
new LatestEvent[Event](eventTarget, "input")
}
def change(eventTarget: EventTarget) = {
new LatestEvent[Event](eventTarget, "change")
}
def abort(eventTarget: EventTarget) = {
new LatestEvent[Event](eventTarget, "abort")
}
def error(eventTarget: EventTarget) = {
new LatestEvent[Event](eventTarget, "error")
}
def timeout(eventTarget: EventTarget) = {
new LatestEvent[Event](eventTarget, "timeout")
}
def load(eventTarget: EventTarget) = {
new LatestEvent[UIEvent](eventTarget, "load")
}
def loadend(eventTarget: EventTarget) = {
new LatestEvent[ProgressEvent](eventTarget, "loadend")
}
def loadstart(eventTarget: EventTarget) = {
new LatestEvent[ProgressEvent](eventTarget, "loadstart")
}
def progress(eventTarget: EventTarget) = {
new LatestEvent[ProgressEvent](eventTarget, "progress")
}
}