Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.59 KB | None | 0 0
  1. ```
  2. once
  3. ```
  4.  
  5. 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:
  6.  
  7. ```
  8. function once(fn, context) {
  9. var result;
  10.  
  11. return function() {
  12. if(fn) {
  13. result = fn.apply(context || this, arguments);
  14. fn = null;
  15. }
  16.  
  17. return result;
  18. };
  19. }
  20.  
  21. ```
  22. Usage
  23. ```
  24. var canOnlyFireOnce = once(function() {
  25. console.log('Fired!');
  26. });
  27.  
  28.  
  29.  
  30. canOnlyFireOnce(); // "Fired!"
  31. canOnlyFireOnce(); // nada
  32. ```
  33.  
  34. The once function ensures a given function can only be called once, thus prevent duplicate initialization!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement