-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy patheventsource.js
More file actions
78 lines (75 loc) · 1.72 KB
/
eventsource.js
File metadata and controls
78 lines (75 loc) · 1.72 KB
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
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2015 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { getRequestToken } from './requesttoken.ts'
/**
* Create a new event source
*
* @param {string} src
* @param {object} [data] to be send as GET
*
* @constructs OCEventSource
*/
function OCEventSource(src, data) {
let dataStr = ''
let name
let joinChar
this.typelessListeners = []
this.closed = false
if (data) {
for (name in data) {
dataStr += name + '=' + encodeURIComponent(data[name]) + '&'
}
}
dataStr += 'requesttoken=' + encodeURIComponent(getRequestToken())
joinChar = '&'
if (src.indexOf('?') === -1) {
joinChar = '?'
}
this.source = new EventSource(src + joinChar + dataStr)
this.source.onmessage = function(e) {
for (let i = 0; i < this.typelessListeners.length; i++) {
this.typelessListeners[i](JSON.parse(e.data))
}
}.bind(this)
// add close listener
this.listen('__internal__', function(data) {
if (data === 'close') {
this.close()
}
}.bind(this))
}
OCEventSource.prototype = {
typelessListeners: [],
/**
* Listen to a given type of events.
*
* @param {string} type event type
* @param {Function} callback event callback
*/
listen: function(type, callback) {
if (callback && callback.call) {
if (type) {
this.source.addEventListener(type, function(e) {
if (typeof e.data !== 'undefined') {
callback(JSON.parse(e.data))
} else {
callback('')
}
}, false)
} else {
this.typelessListeners.push(callback)
}
}
},
/**
* Closes this event source.
*/
close: function() {
this.closed = true
this.source.close()
},
}
export default OCEventSource