function createEventSource(url, options = {}) {
const eventSource = new EventSource(url);
// 添加事件监听器
eventSource.addEventListener('open', options.onOpen);
eventSource.addEventListener('message', options.onMessage);
eventSource.addEventListener('error', options.onError);
// 添加销毁方法
eventSource.destroy = function() {
eventSource.close();
eventSource.removeEventListener('open', options.onOpen);
eventSource.removeEventListener('message', options.onMessage);
eventSource.removeEventListener('error', options.onError);
};
// 返回EventSource对象
return eventSource;
}
使用示例:
const url = 'https://xxx.com/'; // 替换为你的EventSource URL
const options = {
onOpen: function(event) {
console.log('连接已打开');
},
onMessage: function(event) {
console.log('收到消息:', event.data);
},
onError: function(event) {
console.log('发生错误:', event);
}
};
// 创建EventSource对象
const eventSource = createEventSource(url, options);
createEventSource
函数接受两个参数:url
是EventSource的URL,options
是一个可选的配置对象,包含三个回调函数:onOpen
、onMessage
和onError
,分别对应EventSource的open
、message
和error
事件。
你可以根据需要自定义回调函数的逻辑,例如在onOpen
中处理连接已打开的事件,在onMessage
中处理收到的消息,在onError
中处理错误事件。
最后,通过调用createEventSource
函数,传入URL和配置对象,即可创建并返回一个EventSource对象。
请注意,EventSource对象是基于浏览器的原生API,因此只能在浏览器环境中使用。在使用EventSource时,请确保目标服务器支持Server-Sent Events(SSE)协议。
if (typeof (EventSource) !== 'undefined') {
// 操作代码
} else {
console.log('当前浏览器不支持服务器发送的事件');
}