2012-07-09 74 views
1

我如何暂停服务器发送的事件连接?是否有可能,还是必须关闭SSE,然后重新打开并重新分配所有事件处理程序?如何“暂停”服务器发送的事件?

例如,我想这样做(这是所有的理论,我不知道暂停/重启功能名称):

var source = new EventSource(url); 

source.addEventListener("something", somefunction, false); 
source.addEventListener("somethingElse", somefunction2, false); 

//...some code 

source.pause(); 


//...some code 

source.restart(); 

回答

2

是的,这就是技术上需要做的,但你可以将它抽象掉。注意:这一个只连接后,你做.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(); 
+0

我在想这样的事情,但它似乎_hacky_ – Neal 2012-07-09 15:35:53

+4

没什么*哈克*想想,这也正是为什么抽象低层次的结构存在。 – 2012-08-17 02:01:31

+0

函数bindEvents中有一个小错字。在this.es.addEventListener()中,L应该是大写。 – user1915746 2017-03-16 10:08:55