Javascript 回调事件侦听器
我是node的新手,在处理回调时遇到了一些麻烦 我尝试使用单个函数打开或关闭组件的连接,具体取决于组件的当前状态Javascript 回调事件侦听器,javascript,node.js,callback,Javascript,Node.js,Callback,我是node的新手,在处理回调时遇到了一些麻烦 我尝试使用单个函数打开或关闭组件的连接,具体取决于组件的当前状态 if(state){ component.open(function(){ component.isOpen(); //TRUE }); } else{ component.isOpen(); //Always false component.close(); //Results in error, due to port not bein
if(state){
component.open(function(){
component.isOpen(); //TRUE
});
}
else{
component.isOpen(); //Always false
component.close(); //Results in error, due to port not being open
}
基本上,我试图在关闭连接之前等待一段未指定的时间,我想使用我的单数切换函数来关闭它。据我所见,确保端口打开的唯一方法是从回调内部。有没有办法让回调侦听某种事件的发生?或者在回调中接受输入还有其他常见的做法吗 回调意味着只调用一次,而事件是按需调用方法的“可以说”多次,在我看来,您的用例就像您希望按需打开和关闭连接一样,也可以多次 为此,最好使用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
回调不必只调用一次。查看
.forEach()
以了解数组。它为数组中的每个元素调用回调函数。我并不是说(也没有说)它们必须被调用一次,只是指出它们是为了在客户端需要通知已完成的作业时使用。批处理操作是另一种用法,与它看起来的问题无关。我只是回答了你答案的第一句话,这句话不正确。
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...
});