简体   繁体   English

事件监听器中的JavaScript回调

[英]Javascript callback within event listener

I am currently trying to implement a system where a callback is triggered from within an event listener (code below). 我目前正在尝试实现一个从事件监听器(以下代码)中触发回调的系统。 When I run the code, I get the error "callback is not a function", which I believe to be because the variable callback is not defined by the event listener. 运行代码时,出现错误“回调不是函数”,我相信是因为事件侦听器未定义变量回调。

function playSound(no, callback) {
var noOfSounds = sound().length;
if(no == "random" || no == undefined) {
    act("There are "+noOfSounds+" Sounds");
    var randomNo = Math.floor(Math.random() * noOfSounds);
    act("Will use no."+randomNo);
    playSound(randomNo);
} else {
    sound()[no].addEventListener("ended", function() {

        callback();

    });
    sound()[no].play();
}}

I think your problem is the way you are calling the function. 我认为您的问题是调用函数的方式。 If I look at line 10 you are saying 如果我看第10行,你是说

 playSound(randomNo)

It should be 它应该是

 playSound(randomNo, function(){
    //code to execute in callback
});

This is because you are calling trying to use callback which is a function and should be added to the input parameters when calling the method. 这是因为您正在调用尝试使用回调函数,该回调函数是一个函数,在调用该方法时应将其添加到输入参数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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