日期:2014-05-16  浏览次数:20384 次

underscore.js中的debounce解析问题
_.debounce = function(func, wait, immediate) {
    var result;
    var timeout = null;
    return function(){
       .....
        var later = function() {
            timeout = null;
            if (!immediate) result = func.apply(context, args);
      };

       ........
       ........
       ......
   }
   }

下面是模拟输入框查询200毫秒后调用,这儿看underscore.js的源码,这儿需要
传入func参数,但是这儿debounce(200)调用的时候,没有传入函数,为什么没有
报错
<input type="text" id="search" name="search" />  
<script type="text/javascript">  
    var query = _(function() {   
    }).debounce(200);  
  
    $('#search').bind('keypress', query);  
</script>  
------解决方案--------------------
 _.mixin(_);
var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };



_.mixin = function(obj) {
    each(_.functions(obj), function(name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result.call(this, func.apply(_, args));
      };
    });
  };


_.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result.call(this, func.apply(_, args));
      };