In realtà, il tuo codice funzionerà praticamente così com'è, basta dichiarare il callback come argomento e puoi chiamarlo direttamente usando il nome dell'argomento.
Le basi
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);
Che chiamerà doSomething, che chiamerà foo, che avviserà "la roba va qui".
Si noti che è molto importante passare il riferimento alla funzione ( foo), piuttosto che chiamare la funzione e passare il suo risultato ( foo()). Nella tua domanda, lo fai correttamente, ma vale la pena sottolineare perché è un errore comune.
Roba più avanzata
A volte vuoi chiamare il callback in modo che veda un valore specifico per this. Puoi farlo facilmente con la callfunzione JavaScript :
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`
Puoi anche passare argomenti:
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`
A volte è utile passare gli argomenti che si desidera dare al callback come un array, piuttosto che individualmente. Puoi usare applyper farlo:
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)la chiamata deve essere dopo averfunction successdefinito. In caso contrario, verrà visualizzato un errore che indica che la funzione non è definita.