是的,这就是技术上需要做的,但你可以将它抽象掉。注意:这一个只连接后,你做.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();
我在想这样的事情,但它似乎_hacky_ – Neal 2012-07-09 15:35:53
没什么*哈克*想想,这也正是为什么抽象低层次的结构存在。 – 2012-08-17 02:01:31
函数bindEvents中有一个小错字。在this.es.addEventListener()中,L应该是大写。 – user1915746 2017-03-16 10:08:55