All files / fn once.js

100% Statements 7/7
100% Branches 4/4
100% Functions 2/2
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29                                  1x 2x 2x 1x 1x 1x         1x  
/**
 * 包装为仅触发一次的函数
 * - 被包装的函数智能执行一次,之后不会再执行
 * @method fn/once
 * @param {Function} fn 要延迟触发的函数
 * @param {Object} [bind] 函数的 this 指向
 * @returns {Function} 该函数仅能触发执行一次
 * @example
 * var $once = require('@spore-ui/kit/packages/fn/once');
 * var fn = $once(function () {
 *   console.info('output');
 * });
 * fn(); // 'output'
 * fn(); // will do nothing
 */
 
function once(fn, bind) {
  return function () {
    bind = bind || this;
    if (typeof fn === 'function') {
      fn.apply(bind, arguments);
      fn = null;
      bind = null;
    }
  };
}
 
module.exports = once;