Ich verstehe die Übergabe einer Funktion an eine andere Funktion als Rückruf und deren Ausführung, aber ich verstehe nicht die beste Implementierung, um dies zu tun. Ich suche ein sehr einfaches Beispiel wie dieses:
var myCallBackExample = {
myFirstFunction : function( param1, param2, callback ) {
// Do something with param1 and param2.
if ( arguments.length == 3 ) {
// Execute callback function.
// What is the "best" way to do this?
}
},
mySecondFunction : function() {
myFirstFunction( false, true, function() {
// When this anonymous function is called, execute it.
});
}
};
Wenn ich in myFirstFunction new callback () zurückgebe, funktioniert es und führt die anonyme Funktion aus. Dies scheint mir jedoch nicht der richtige Ansatz zu sein.
Sie können nur sagen
callback();
Alternativ können Sie die Methode call
verwenden, wenn Sie den Wert von this
innerhalb des Rückrufs anpassen möchten.
callback.call( newValueForThis);
Innerhalb der Funktion würde this
sein, was auch immer newValueForThis
ist.
Sie sollten prüfen, ob der Rückruf existiert und eine ausführbare Funktion ist:
if (callback && typeof(callback) === "function") {
// execute the callback, passing parameters as necessary
callback();
}
Viele Bibliotheken (jQuery, Dojo usw.) verwenden ein ähnliches Muster für ihre asynchronen Funktionen sowie node.js für alle asynchronen Funktionen (nodejs übergibt normalerweise error
und data
an Rückrufen). Ein Blick in den Quellcode würde helfen!
Es gibt 3 Hauptmöglichkeiten, um eine Funktion auszuführen:
var callback = function(x, y) {
// "this" may be different depending how you call the function
alert(this);
};
Welche Methode Sie wählen, hängt davon ab, ob:
Dokumente für Function.call , Function.apply
Rückrufe beziehen sich auf Signale und "neu" auf das Erstellen von Objektinstanzen.
In diesem Fall wäre es noch sinnvoller, nur "callback ()" auszuführen. als "return new callback ()", weil Sie sowieso nichts mit einem Rückgabewert tun.
(Und der arguments.length == 3 Test ist wirklich klobig, fwiw, besser zu überprüfen, dass Callback-Parameter existiert und eine Funktion ist.)
die ordnungsgemäße Umsetzung wäre:
if( callback ) callback();
dadurch ist der Rückrufparameter optional.
Sie können verwenden:
if (callback && typeof(callback) === "function") {
callback();
}
Das folgende Beispiel ist etwas umfassender:
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
var sandwich = {
toppings: [param1, param2]
},
madeCorrectly = (typeof(param1) === "string" && typeof(param2) === "string") ? true : false;
if (callback && typeof(callback) === "function") {
callback.apply(sandwich, [madeCorrectly]);
}
}
mySandwich('ham', 'cheese', function(correct) {
if (correct) {
alert("Finished eating my " + this.toppings[0] + " and " + this.toppings[1] + " sandwich.");
} else {
alert("Gross! Why would I eat a " + this.toppings[0] + " and " + this.toppings[1] + " sandwich?");
}
});
function checkCallback(cb) {
if (cb || cb != '') {
if (typeof window[cb] === 'undefined') alert('Callback function not found.');
else window[cb].call(this, Arg1, Arg2);
}
}
Hier ist ein einfaches Beispiel, das die Funktion callback()
in JavaScript erklärt:
var x = 0;
function testCallBack(param1, param2, callback) {
alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);
if (callback && typeof(callback) === "function") {
x += 1;
alert("Calla Back x= " + x);
x += 1;
callback();
}
}
testCallBack('ham', 'cheese', function() {
alert("Function X= " + x);
});