Keine Beschreibung

once.js 935B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var wrappy = require('wrappy')
  2. module.exports = wrappy(once)
  3. module.exports.strict = wrappy(onceStrict)
  4. once.proto = once(function () {
  5. Object.defineProperty(Function.prototype, 'once', {
  6. value: function () {
  7. return once(this)
  8. },
  9. configurable: true
  10. })
  11. Object.defineProperty(Function.prototype, 'onceStrict', {
  12. value: function () {
  13. return onceStrict(this)
  14. },
  15. configurable: true
  16. })
  17. })
  18. function once (fn) {
  19. var f = function () {
  20. if (f.called) return f.value
  21. f.called = true
  22. return f.value = fn.apply(this, arguments)
  23. }
  24. f.called = false
  25. return f
  26. }
  27. function onceStrict (fn) {
  28. var f = function () {
  29. if (f.called)
  30. throw new Error(f.onceError)
  31. f.called = true
  32. return f.value = fn.apply(this, arguments)
  33. }
  34. var name = fn.name || 'Function wrapped with `once`'
  35. f.onceError = name + " shouldn't be called more than once"
  36. f.called = false
  37. return f
  38. }