Search code examples
javascriptmeteorunderscore.jsiron-routerlodash

_.debounce and Iron.controller() in eventmap


I want to implement a debounced search with iron-router where the search query is written into the controllers state. unfortunately the only way I could get _.debounce to work is to pass it directly to the event map like so:

Template.search.events({
  'keydown #search': _.debounce(function(event) {
    var controller = Iron.controller();
   }, 750)
});

unfortunately Iron.controller() doesn't know the context here so an error drops.

But if I nest the debounce inside a function to get the Iron.controller(), _.debounce never fires.

Template.search.events({
  'keydown #search': function(event) {
    var state = Iron.controller().state;
    var q = $(event.currentTarget).val();
    _.debounce(function() {
      state.set("q", q);
    }, 750);
  }
});

Has anybody done something similar and a solution to this problem?


Solution

  • I'm not familiar with debounce, but if I'm not mistaking, the following should work:

    var doIt = _.debounce(function(func){
        func()
    }, 750);
    
    Template.search.events({
      'keydown #search': function(event) {
        var state = Iron.controller().state;
        var q = $(event.currentTarget).val();
        doIt(function(){
            state.set("q", q);
        })
      }
    });