Created
January 27, 2018 07:15
-
-
Save amitmbee/1472fc6be0f1bbb41043b22c921bc861 to your computer and use it in GitHub Desktop.
Once - Can call a callback(eventHandlers mostly) only once, returns undefined the second time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//once | |
//There are times when you prefer a given functionality only happen once, similar to the way you'd use an onload event. //This code provides you said functionality: | |
function once(fn, context) { | |
var result; | |
return function() { | |
if(fn) { | |
result = fn.apply(context || this, arguments); | |
fn = null; | |
} | |
return result; | |
}; | |
} | |
// Usage | |
var canOnlyFireOnce = once(function() { | |
console.log('Fired!'); | |
}); | |
canOnlyFireOnce(); // "Fired!" | |
canOnlyFireOnce(); // nada | |
//How it Works | |
//A function is passed to once(fn) as an argument. once() executes the callback function once and assignes null as the value of callback. Since, Javascript function are passed by reference, fn=null means the the original callback function also points to a null value. Hence the callback cannot be fired the second time |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment