回调Eventlistener

时间:2016-03-07 01:47:28

标签: javascript node.js callback

我是节点的新手,并且在回调时遇到了一些麻烦。

我正在尝试使用单个功能打开组件的连接,或者根据它的当前状态关闭它。

if(state){
   component.open(function(){
       component.isOpen(); //TRUE
   });
}
else{
    component.isOpen(); //Always false 
    component.close(); //Results in error, due to port not being open
}

基本上我试图在关闭连接之前等待一段不确定的时间,我想用我的单一切换功能关闭它。从我所看到的,保证端口打开的唯一方法是从回调内部。有没有办法让回调听某种事件发生?或者是否有其他一些接受回调输入的常见做法?

1 个答案:

答案 0 :(得分:0)

回调意味着要被调用一次,而事件是按需调用方法的,所以要说#39;多次,您的用例在我看来就像您想要按需打开和关闭连接以及多次......

为此,最好使用EventEmitter,它是nodejs的一部分,并且非常易于使用。

例如:

var EventEmitter = require('events').EventEmitter;

var myEventEmitter = new EventEmitter();
myEventEmitter.on('toggleComponentConnection', function () {
   if (component.isOpen()) {
      component.close();
   }
   else {
      component.open(function(){
         component.isOpen(); //TRUE
      });
   }
});

...
// Emit your toggle event at whatever time your application needs it
myEventEmitter.emit('toggleComponentConnection');

否则,如果您选择使用回调,则需要牢记功能范围和javascript closures

function toggleComponentConnection(callback) {
   if (component.isOpen()) {
       component.close(function () {
          callback();
       });
   }
   else {
      component.open(function(){
         component.isOpen(); //TRUE
         callback();
      });
   }
}

...
// Call your toggle function at whatever time your application needs it
toggleComponentConnection(function () {
   component.isOpen();

   // make sure your application code continues from this scope...
});
相关问题