× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Javascript Callback

Ethan
Jan 25, 2016
<p>Had do you ever wonder how to use the so-sounds callbacks on javascript? or basically in short term what they are?</p> <p>In a short-term a callback its a function to call-back later when some other function its done.</p> <p>Okay enough bla bla and more code code.</p> <p><strong>Lets put a real world example.</strong></p> <p>Lets say you want to read a file and then when the file is readed you want to take the result and display an image preview.</p> <p>So we are going to use the native <a href="https://developer.mozilla.org/es/docs/Web/API/FileReader">File Reader</a></p> <p>First lets declare our handler.</p> <pre><code>$( 'input' ).change(function() { var file = $(this)[0].files[0]; // this will take the file readFile(file, function(event){ console.log(event.target.result) // this will be the encode base64 string }); });</code></pre> <p>Did you notice that we are passing a second parameter as a non-named function? that its our callback, take in note that you can also pass the function like this.</p> <pre><code>$( 'input' ).change(function() { var file = $(this)[0].files[0]; // this will take the file readFile(file, doSomethingWithFile); }); doSomethingWithFile = function(event){ console.log(event.target.result) // this will be the encode base64 strin };</code></pre> <p>So both will work, depending on your taste, now lets create our readFile function.</p> <pre><code class="language-javascript">readFile = (file, callback){ var reader = new FileReader(); reader.onloadend = callback; reader.readAsDataURL(file); };</code></pre> <p>So basically what this function its doing is.</p> <p>Take a file and a callback as a paremeter.</p> <p>it initialize an instance of the class fileReader.</p> <p>then it tell it "on file loaded" invoke the callback, <strong>note </strong></p> <p><a href="https://developer.mozilla.org/es/docs/Web/API/FileReader">This event is triggered each time the reading operation is successfully completed.</a></p> <p>then we are telling the reader, "read this file as DataURL".</p> <p>And whoala, you are now handling callbacks like a master.</p>
comments powered by Disqus