是的,这就是技术上需要发生的事情,但您可以将其抽象出来。注意:这个只有在你完成后才能连接.connect()
function EventSource2(url) {
this.url = url;
this.es = null;
this.listeners = {};
}
EventSource2.prototype = {
constructor: EventSource2,
connect: function() {
this.es = new EventSource(this.url);
this.bindEvents();
},
disconnect: function() {
this.es.close();
this.es = null;
},
bindEvents: function() {
for ( var type in this.listeners ) {
var evs = this.listeners[type];
for( var i = 0; i < evs.length; ++i ) {
this.es.addEventlistener( type, evs[i], false );
}
}
},
addEventListener: function( type, fn ) {
if( !this.listeners[type] ) {
this.listeners[type] = [];
}
this.listeners[type].push( fn );
if( this.es ) {
this.bindEvents();
}
}
}
用法:
var source = new EventSource2(url);
source.addEventListener("something", somefunction, false);
source.addEventListener("somethingElse", somefunction2, false);
source.connect();
source.disconnect();
source.connect();