简体   繁体   中英

Callback Eventlistener

I am new to node, and having a bit of trouble wrapping my mind around callbacks.

I am trying to use a single function to either open a component's connection, or close it, depending upon it's current state.

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

Basically I am trying to wait for an unspecified amount of time before closing my connection, and I would like to close it using my singular toggle function. From what I have seen, the only way to guarantee that the port is open, is from inside the callback. Is there a way to have a callback listen for some kind of event to take place? Or is there some other common practice for accepting input in a callback?

Callbacks are meant to be called once whereas events are there to invoke methods on demand 'so to speak' multiple times, your use case appears to me like you would want to open and close connection on demand as well as multiple times...

For this it is better to use EventEmitter which is part of nodejs and is really easy to use.

For example:

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');

Otherwise, if you choose to use callbacks, you need to keep in mind function scope and 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...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM