ng-ampere-debounce似乎停止在AngularJS 1.2中工作

mur*_*ton 2 angularjs firebase debouncing angularjs-directive

我一直在使用jQuery/AngularJS指令在Firebase支持的应用程序中对输入进行去抖动.它来自Lars Gersmann的帖子,并且工作得很好:

http://orangevolt.blogspot.com.au/2013/08/debounced-throttled-model-updates-for.html

从Angular 1.0.8更新到1.2似乎打破了局面.每次指令触发时,$ ._ data函数都会返回一个未定义的错误,而不是从元素中提取事件,从而导致出现此错误:

TypeError:Object.keys在Function.keys(native)上的非对象上调用

它在这里定义:

 var map = $._data( element[0], 'events'),
 events = $.each( Object.keys( map), function( index, eventName) {
    // map is undefined :(
    ...
 }
Run Code Online (Sandbox Code Playgroud)

AngularJS甚至是jQuery中的某些东西是否会像过去那样拉动这个元素的事件?

(旁注,我使用的是jQuery版本1.8.3,在Angular升级中没有改变).

感谢任何能够对此有所了解的人!

Tom*_*and 6

您可以通过使用unbinds,binds和Angular $timeout方法来创建更简单的去抖动脚本来访问这些事件.这是基于阻止事件的这篇文章ngChange.

这是一个重写的debounce指令,似乎在Angular 1.2中有效.它取消绑定输入,然后$setViewValue在1000ms延迟后应用更改.我还添加了模糊的即时更改.使这项工作超过原始职位的关键是确定优先权.

angular.module('app', []).directive('ngDebounce', function($timeout) {
return {
    restrict: 'A',
    require: 'ngModel',
    priority: 99,
    link: function(scope, elm, attr, ngModelCtrl) {
        if (attr.type === 'radio' || attr.type === 'checkbox') return;

        elm.unbind('input');

        var debounce;
        elm.bind('input', function() {
            $timeout.cancel(debounce);
            debounce = $timeout( function() {
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(elm.val());
                });
            }, 1000);
        });
        elm.bind('blur', function() {
            scope.$apply(function() {
                ngModelCtrl.$setViewValue(elm.val());
            });
        });
    }

}
});
Run Code Online (Sandbox Code Playgroud)

再加上JSFiddle演示