在JavaScript中创建自定义回调 [英] Create a custom callback in JavaScript
问题描述
我需要做的就是在当前函数执行结束时执行回调函数。
All I need to do is to execute a callback function when my current function execution ends.
function LoadData()
{
alert('The data has been loaded');
//Call my callback with parameters. For example,
//callback(loadedData , currentObject);
}
此功能的消费者应该是这样的:
A consumer for this function should be like this:
object.LoadData(success);
function success(loadedData , currentObject)
{
//Todo: some action here
}
我该如何实现?
推荐答案
实际上,你的代码将几乎按原样工作,只需将你的回调声明为参数,你可以使用参数名称直接调用它。
Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.
function doSomething(callback) {
// ...
// Call the callback
callback('stuff', 'goes', 'here');
}
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}
doSomething(foo);
这将调用 doSomething
,这将调用 foo
,它会提醒东西在这里。
That will call doSomething
, which will call foo
, which will alert "stuff goes here".
注意传递函数引用( foo
),而不是调用函数并传递结果( foo()
) 。在你的问题中,你做得恰当,但它值得指出,因为这是一个常见的错误。
Note that it's very important to pass the function reference (foo
), rather than calling the function and passing its result (foo()
). In your question, you do it properly, but it's just worth pointing out because it's a common error.
有时你想调用回调,因此它会看到这个
的特定值。您可以使用JavaScript 调用
函数轻松完成此操作:
Sometimes you want to call the callback so it sees a specific value for this
. You can easily do that with the JavaScript call
function:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}
function foo() {
alert(this.name);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`
您还可以传递参数:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
}
function foo(salutation) {
alert(salutation + " " + this.name);
}
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`
有时传递你想要的参数很有用将回调作为数组提供,而不是单独提供。您可以使用 apply
来执行此操作:
Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply
to do that:
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
}
function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe - 3 2 1" via `foo`
这篇关于在JavaScript中创建自定义回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!