Anonymous
Anonymous

Reputation: 6251

Best way to add an event with delay in Meteor?

I'm adding search functionality to a meteor app and want to trigger a search after a keyup event, plus 500ms or so. I don't want to call my meteor method on the server after every single keyup, since if somebody enters a sentence that's going to be... a lot of calls.

How can I add a delay to the keyup event of 500ms, but have the triggered event cancelled if another keyup event is detected?

Upvotes: 1

Views: 914

Answers (2)

Ankur Soni
Ankur Soni

Reputation: 6008

Answered After 3 years

The accepted answer is confusing with the question as the question says "Best way to add an event with delay in Meteor?".

Currently Meteor 1.5.2 is latest, Below is the exact expected functionality from the question.

Default way of writing an event listener activity

Template.YourTemplateName.events({
    // inputs with either id/class as "search"
    'input #search, input .search': function(event, template){
      console.log('Searching.');
    }
});

Adding Event with Expected delay to action

Template.YourTemplateName.events({
    // inputs with either id/class as "search"
    'input #search, input .search': _.debounce(function(event, template){
      console.log('Searching.');
    }, 1000)
});

underscore comes by default, you may install lodash using command meteor npm install lodash. Then import lodash to your js file as import _ from 'lodash';

Upvotes: 1

Seth Malaki
Seth Malaki

Reputation: 4486

Use the underscore package's debounce function. You might need to add underscore to your project via meteor add underscore. But I think it's already included by default.

var doSearch = _.debounce(function() {
   // do your search
}, 500);

More info: http://underscorejs.org/#debounce

Upvotes: 3

Related Questions