load()函数如何允许用户提供回调? [英] How does the load() function allow the user to provide a callback?
本文介绍了load()函数如何允许用户提供回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在javascript中,对于库/框架来说,让我们定义一个用于对数据进行后处理的回调函数非常流行.
In javascript it's very popular for libraries/frameworks to let us define a callback function for post-processing of data.
例如
load("5", function(element) {
alert(element.name);
});
我想知道load()函数看起来如何能够让用户提供回调?
I wonder how the load() function looks like to be able to let the user provide a callback?
是否有很好的教程?
推荐答案
好吧, load
函数看起来像这样:
Well, the load
function could look like this:
function load(arg, callback) {
var element = { name: "foo " + arg }; // something to pass
if (typeof callback == 'function') {
callback(element);
}
}
通过 typeof
检查,确保回调参数是我们可以调用的对象,即函数.
With the typeof
check we make sure that the callback argument is an object that we can invoke, a function.
然后是您的示例:
load("5", function(element) {
alert(element.name); // Will show `"foo 5"`.
});
这篇关于load()函数如何允许用户提供回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文