在es6中,使用回调函数将事件侦听器转换为iterable

时间:2015-04-05 07:42:51

标签: javascript iterator listener generator

我的websocket类Wws使用onmessage侦听所有传入的消息。

对于使用Wws的程序,我的websocket模块,我希望他们能够"听"通过iterable s。

例如,

// listen for new blog messages
let itr = ws.listen( 'blog', 'new' );

// display each new blog as we receive it
while( true ) {
  let blog = itr.next().value;
  dispBlog( blog );
}

任何数量的iterable都可能挂在事件监听器上。

您如何在generator模块中编写ws

ws = function() {
  conn = new Websocket(...);

  // could have global `onmessage` that passes through the messages
  conn.onmessage = function(msg) {
    // can look at listeners and know there are iterators
    // but how to talk to them?
  }
  listeners = new Map();

  // generator for listening to incoming messages
  listener = function*( service, action ) {
    // can add this service.action to listeners, but what?
    // does this guy create his own `onmessage`?
    // if so, how does he get the `yield` to the outer function?
  }

如何将listenercallback转换为iterator

0 个答案:

没有答案