回调函数和事件处理程序之间的区别



我最近开始了web开发,似乎无法理解事件处理程序和回调函数。我知道事件处理程序是一种回调,它们对事件的响应不同于更通用的回调定义,后者在运行结束时由其他代码调用。但是,我正在寻找一个"坚持"我的解释。

这里有一个的例子

<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>

在这个代码示例中,我知道ready和click都是事件,所以$("button").click(function(){是ready事件的事件处理程序?CCD_ 2是点击事件的事件处理程序?藏起来怎么样?这也是一个事件吗?

是的,这是正确的(我花了一秒钟才意识到你只是在显示你所指的处理程序的内容(。如果您不以内联方式定义处理程序/回调,并为它们提供描述性名称,则会更清楚:

function readyHandler() {
$("button").click(clickHandler);
}
function clickHandler() {
$("p").hide("slow", hideAnimationCompleteCallback);
}
function hideAnimationCompleteCallback() {
alert("The paragraph is now hidden");
}
$(document).ready(readyHandler);

请注意,上面的代码与您的原始代码略有不同,看起来更像:

function readyHandler() {
function clickHandler() {
function hideAnimationCompleteCallback() {
alert("The paragraph is now hidden");
}
$("p").hide("slow", hideAnimationCompleteCallback);
}
$("button").click(clickHandler);
}
$(document).ready(readyHandler);

但是,由于没有一个处理程序/回调依赖于它是在处理程序/回叫中创建的,因此完全独立地显示它们似乎更清楚。但是,如果他们使用的东西只在他们创建的处理程序的范围内,那就很重要了

回调函数就是您所描述的。将函数作为参数传递给另一个函数;回叫";。

示例:

file.read(fileName, function (err, data) {
// once file reading has finished, this function body is called,
// so this anonymous function is the callback
});

事件处理程序是在特定事件发生时触发的函数。它可以用于合成事件、websocket事件等。它通常的语法是使用回调。

示例:

eventBus.on('new_message_arrived', function (err, data) {
// when 'new_message_arrived' event happens, this callback will be called
});
button.click((event) => {
// when button gets clicked, this callback (now used arrow function notaion)
// will be called with the details of the UI event
});

最新更新