重置 _.after 计数器

Reset _.after counter

我在网上查了一下,但我找不到在执行完内部代码后重置 _.after 计数器的方法。在此示例中,我的预期功能将意味着只有每点击 5 次按钮才会显示警告框:

var cb;

cb = _.after(4, function() {
    alert(':)');
});

$('button').on('click', cb);

http://jsfiddle.net/danharper/JkcuD/

您无法重置甚至无法查看计数器,因为计数器是私有的:

来自:http://underscorejs.org/docs/underscore.html#section-87

 _.after = function(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

也就是说,您可以看到那里没有太多代码,因此将它调整为 运行 一次很容易:

 _.onceEvery= function(times, func) {
    var orig = times;
    return function() {
      if (--times < 1) {
        times=orig;
        return func.apply(this, arguments);
      }
    };
  };

示例:http://jsfiddle.net/JkcuD/78/