Create a custom callback in JavaScript -
All I have to do is execute the callback function when my current function is executed.
function load data () {warning ('data is loaded'); // Call your callback with parameters, for example, // callback (loaded data, current object); }
For this function the consumer should be:
object.LoadData (success);
How do I apply it? In fact, your code will work a lot, just declare your callback as an argument and you can call it directly using the logic name. .
Basics
function doSomething (callback) {// ... // Callback callback call ('luggage', 'goes',' here ');} Function foo (a, b, c) {// callback warning (a + "+ + b +" "+ c); } DoSomething (foo);
This will call doSomething
, which will call foo
, which will warn the "stuff goes here".
Note that instead of sending the function and its result ( foo ()
), the function reference ( foo
) Is very important to pass. In your question, you do it properly, but this is just one thing, because it is a common error.
More advanced stuff
Sometimes you want to call callback, so this is a specific code for this this
you call javascript You can do this easily with the
function:
function thing (name) {this.name = name; } Thing.prototype.do Some = function (callback) {// Call our callback, but reference callback. (This) using your own example; } Function foo () {warning (this.name); } Var t = New Thing ('Joe'); T.doSomething (foo); // Alert "Joe" through 'Foo'
You can also pass the argument:
function thing (name) {this.name = Name; } Thing.prototype.doSomething = call (callback, salutation) {// Call our callback, but use your own example as reference callback.col (this, hello); } Function foo (Hello) {Warning (Hello + "+ this.name);} Var t = New Thing ('Joe'); T.D. (Afu, 'Hi'); // Alert" Hi Joe " Through medium 'Foo'
is sometimes useful for passing different arguments, which you want to give to the callback as an array. You can use to apply
:
function thing (name) {this.name = name;} Thing.prototype.doSomeething = function (Callback) {// call our callback But using the context of your own example as a reference callback. (This, ['hi', 3, 2, 1]);} ceremony foo (Hello, three, two, one) {Warning (+ Hello + "+ This.name +" - "+ 3 +" + + + + + + + + +);} Var t = New Thing ('joe'); t.doSomething (foo); // Warning "Hi Joe - 3 2 1" by `Foo '
Comments
Post a Comment