javascript - Callback Eventlistener -
i new node, , having bit of trouble wrapping mind around callbacks.
i trying use single function either open 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 port not being open } basically trying wait unspecified amount of time before closing connection, , close using singular toggle function. have seen, way guarantee port open, inside callback. there way have callback listen kind of event take place? or there other common practice accepting input in callback?
callbacks meant called once whereas events there invoke methods on demand 'so speak' multiple times, use case appears me want open , close connection on demand multiple times...
for better use eventemitter part of nodejs , easy 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 toggle event @ whatever time application needs myeventemitter.emit('togglecomponentconnection'); otherwise, if choose use callbacks, need keep in mind function scope , javascript closures.
function togglecomponentconnection(callback) { if (component.isopen()) { component.close(function () { callback(); }); } else { component.open(function(){ component.isopen(); //true callback(); }); } } ... // call toggle function @ whatever time application needs togglecomponentconnection(function () { component.isopen(); // make sure application code continues scope... });
Comments
Post a Comment