実際、コードはほとんどそのまま機能します。コールバックを引数として宣言するだけで、引数名を使用して直接呼び出すことができます。
基礎
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
、「ものをここに」警告であろう。
関数を呼び出してその結果()を渡すのではなく、関数参照(foo
)を渡すことが非常に重要であることに注意してくださいfoo()
。あなたの質問では、あなたはそれを適切に行いますが、それは一般的なエラーであるため、指摘するだけの価値があります。
より高度なもの
コールバックを呼び出して、の特定の値を確認したい場合がありますthis
。これはJavaScript call
関数で簡単に実行できます。
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
はそれを行うために使用できます:
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`
object.LoadData(success)
呼び出しは定義された後でfunction success
ある必要があります。そうしないと、関数が定義されていないことを示すエラーが発生します。