programing

워치를 디바운스 또는 스로틀 할 수 있습니까?워치를 디바운스 또는 스로틀 할 수 있습니까?비스듬히_lodash를 사용하는 JS?비스듬히_lodash를 사용하는 JS?

lastcode 2023. 2. 17. 21:04
반응형

워치를 디바운스 또는 스로틀 할 수 있습니까?비스듬히_lodash를 사용하는 JS?

나는 다음 것을 가지고 있다.<input>scope.id로 바인드 되어 있습니다.입력 필드 값이 변경될 때마다 워치 기능이 실행됩니다.

$scope.$watch("id", function (id) {

   // code that does something based on $scope.id

});

사용자가 값을 변경하는 동안 각 키 누르기에서 코드가 실행되지 않도록 타임아웃을 설정하거나 _lodash를 사용하여 이 값을 디바운스할 수 있는 방법이 있습니까?

사용자가 입력을 정지한 후 워치 내부의 코드 블록이 실행되도록 1초의 지연을 희망합니다.입력값은 언제든지 변경될 수 있습니다.예를 들어 값이 "1" 또는 "10" 또는 "1000"인 경우 함수를 호출해야 합니다.이것은 구글에서 제안이 있는 검색창이 작동하는 방식과 비슷합니다.사용자가 999로 입력하면 함수를 호출해야 합니다.만약 그가 9를 삭제해서 99가 되면, 나는 함수를 호출해야 한다.

저는 _lodash를 이용할 수 있기 때문에 그것을 사용하는 솔루션이 제 요구에 가장 적합할 것입니다.

Angular 1.3.0에서 ngModelOptions를 사용할 수 있습니다.

HTML:

<div ng-controller="Ctrl">
  <form name="userForm">
    Name:
    <input type="text" name="userName"
           ng-model="user.name"
           ng-model-options="{ debounce: 1000 }" />
    <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  </form>
  <pre>user.name = <span ng-bind="user.name"></span></pre>
</div>

상세정보 : https://docs.angularjs.org/api/ng/directive/ngModelOptions

그게 당신이 찾고 있는 건가요?

$scope.$watch("id", _.debounce(function (id) {
    // Code that does something based on $scope.id
    // This code will be invoked after 1 second from the last time 'id' has changed.
}, 1000));

단, 그 함수 내에서 $scope를 변경하려면 그것을 랩해야 합니다.$scope.$apply(...)마치 그런 것처럼_.debounce함수의 용도$timeout내부적으로는 (제가 알기론 그렇지 않습니다) Angular는 이 변경에 대해 알지 못할 것입니다.$scope.

갱신하다

업데이트된 질문에 대해 - 네, 콜백 함수 본문 전체를

$scope.$apply():

$scope.$watch("id", _.debounce(function (id) {
    // This code will be invoked after 1 second from the last time 'id' has changed.
    $scope.$apply(function(){
        // Code that does something based on $scope.id
    })
}, 1000));

그 질문이 로더쉬 솔루션을 요구하는 것을 알고 있습니다.어쨌든 각도 전용 솔루션을 다음에 제시하겠습니다.

app.factory('debounce', function($timeout) {
    return function(callback, interval) {
        var timeout = null;
        return function() {
            $timeout.cancel(timeout);
            var args = arguments;
            timeout = $timeout(function () { 
                callback.apply(this, args); 
            }, interval);
        };
    }; 
}); 

컨트롤러 내:

app.controller('BlaCtrl', function(debounce) {

    $scope.$watch("id", debounce(function (id) {
        ....
    }, 1000));

});

이것을 디렉티브로 캡슐화할 수 있습니다.출처 : https://gist.github.com/tommaitland/7579618

<input type="text" ng-model="id" ng-debounce="1000">

자바스크립트

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;
          }

          var delay = parseInt(attr.ngDebounce, 10);
          if (isNaN(delay)) {
              delay = 1000;
          }

          elm.unbind('input');

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

언급URL : https://stackoverflow.com/questions/21088845/can-i-debounce-or-throttle-a-watched-input-in-angularjs-using-lodash

반응형