Tatsächlich funktioniert Ihr Code so wie er ist. Deklarieren Sie einfach Ihren Rückruf als Argument, und Sie können ihn direkt mit dem Argumentnamen aufrufen.
Die Grundlagen
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);
Das wird anrufen doSomething, das wird anrufen foo, das wird alarmieren "Zeug geht hierher".
Beachten Sie, dass es sehr wichtig ist , um die Funktion zu übergeben Referenz ( foo), anstatt die Funktion aufrufen und das Ergebnis vorbei ( foo()). In Ihrer Frage machen Sie es richtig, aber es lohnt sich nur darauf hinzuweisen, weil es ein häufiger Fehler ist.
Fortgeschrittenere Sachen
Manchmal möchten Sie den Rückruf aufrufen, damit ein bestimmter Wert für angezeigt wird this. Mit der JavaScript- callFunktion können Sie dies ganz einfach tun :
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`
Sie können auch Argumente übergeben:
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`
Manchmal ist es nützlich, die Argumente, die Sie dem Rückruf geben möchten, als Array und nicht einzeln zu übergeben. Sie können dies verwenden apply, um:
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)Anruf muss nachfunction successdefiniert sein. Andernfalls erhalten Sie eine Fehlermeldung, dass die Funktion nicht definiert ist.