edit-article
Home
Up
Delete
Article Name:
Article Description:
by Don Sagrott - Understanding 'callbacks' - this fundamental programming practice is a very simple and very effective method to
Chapter ID/Name:
Status:
Write
Writing
Written
Add Photo:
Owner ID:
Content:
use HTML
Edit Content
<h1 style="text-align: center;">callback - overview</h1> <h2>[WHAT]</h2> <ol> <li>[] a 'callback' refers to a function that we are passing into another function as an arguement. </li> </ol> <h2>[WHY]</h2> <ol> <li>[] the callback function that we pass into the calling function(aka the callee), will be executed once the callee function has completed execution. <em></em></li> </ol> <h2>[WHERE]</h2> <ol> <li><strong>[] <a href="/view/article?id=1765" target="_blank">callback</a></strong> - a primer on using callbacks,</li> </ol> <h2>[WHEN]</h2> <ol> <li>[] to use a callback - when you want to execute another function immediately after the current function has completed its own execution</li> </ol> <h2>[EXAMPLE]</h2> <ol> <li><strong>first function</strong></li> </ol> <div>getDirectionsToLocation(callback){</div> <div> var directions = "head 4 miles east, turn right at stop sign.Then head 2mile west. location is on left hand side of road"</div> <div> callback;</div> <div>}</div> <div><ol> <li><strong>second function</strong></li> </ol></div> <div>travelToLocation(){</div> <div> </div> <div>}</div> <div>getDirectionsToLocation(travelToLocation);</div> <h2>[HOW-TO]</h2> <ol> <li><strong>] pass a callback by reference</strong></li> <ol> <li>] in the above example we passed the callback arguement(doSomethingMore) by reference,</li> </ol> <li><strong>] pass a callback by value</strong></li> <ol> <li>] we can also pass callback arguements by value, aka we are passing the function body as the arguement</li> <li>] doSomething(function(){console.log name;})</li> </ol></ol> <h2>[REFERENCE]</h2> <ol> <li>]</li> </ol> <div>( aka higher order function)</div> <div><ol> <li>// PASTE the first function into your javascript console and execute it, nothing will happen</li> <li>] function doSomething(){</li> <li> var message = "hello";</li> <li>}</li> <li>// PASTE the following function,</li> <li>] function doSomethingMore(){</li> <li> console.log name;</li> <li>// PASTE the following function call into the console window and run it, CONGRATS you just created your first callback</li> <li>] doSomething(doSomethingMore);</li> </ol></div>