Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I use _lodash debounce with AngularJS?

It was suggested I could use the following:

$wmdInput.on('keyup', _.debounce(function () {
    var rawContent = $wmdInput.val();
    scope.$apply(function () {
        ngModel.$setViewValue(rawContent);
    });
}), 300);

However this gives a message: Uncaught TypeError: Object 500 has no method 'apply' from jQuery.

Does anyone know how I could fix this?

As an FYI it was also suggested I could use the following:

var promise;
$wmdInput.on('keyup', function () {
    $timeout.cancel(promise);
    promise = $timeout(function() {
        var rawContent = $wmdInput.val();
        ngModel.$setViewValue(rawContent);
    }, 2000);
});

I would appreciate comments from the AngularJS experts here. Would the second code work as well as using _lodash? I noticed a lot of posts on github so I hope to see something implemented in the core AngularJS soon.

Upvotes: 0

Views: 1187

Answers (1)

robertklep
robertklep

Reputation: 203241

The (now deleted) answer from @Satpal was correct: you are passing the timeout value (300) as an argument to $wmdInput.on, and not _.debounce.

So try this:

$wmdInput.on('keyup', _.debounce(function () {
  var rawContent = $wmdInput.val();
  scope.$apply(function () {
    ngModel.$setViewValue(rawContent);
  });
}, 300));

Upvotes: 1

Related Questions