Delay (debounce) ajax request with coffeescript

2019-08-10 08:56发布

问题:

I'm using CoffeeScript in my rails app, and I need to delay a remote ajax form submission, the main problem I'm having is debouncing the request so that the form will send once 250ms has passed without the user typing in the the form.

Right now I have something that looks like this going on, obviously it won't work so this has some debug output in it to help me out.

Taking a look at the table below, you should know that the function that I want to be "debounced" is within the element.keyup (event) -> function, any help would be amazing!

remoteTable =

  bindEvents: (element) ->
    element.keyup (event) ->
      console.log(event)


  send: (event) ->
    console.log(event)

** It would be really helpful if I could gather a few examples of how this works? ** I did see the way that underscore.js does it, but Here, this is my old method: I just can't wrap my head around how this should wok:

http://davidwalsh.name/function-debounce

回答1:

You can use a simple timeout for this, no need to get fancy.

remoteTable =
  bindEvents: (element) ->
    timeout = null
    element.keyup (event) ->
      clearTimeout(timeout)
      timeout = setTimeout(remoteTable.send, 250)

  send: ->
    console.log('Sending request...')


回答2:

I played around on coffeescript.org where they have a online "try coffeescript" translator/runner and it seems

remoteTableOrg =
  bindEvents: (element) ->
    element.keyup (event) ->
      console.log(event)
  send: (event) ->
    console.log(event)

Translates into

var remoteTableOrg;

remoteTableOrg = {
  bindEvents: function(element) {
    return element.keyup(function(event) {
      return console.log(event);
    });
  },
  send: function(event) {
    return console.log(event);
  }
};

So element.keyup is actually a function invocation with a function as a parameter.

Seeing this, I tried

remoteTable =
  bindEvents: (element) ->
    element.keyup _.debounce((event) ->
      console.log(event)
    ,250)
  send: (event) ->
    console.log(event)

and got:

var remoteTable;

remoteTable = {
  bindEvents: function(element) {
    return element.keyup(_.debounce(function(event) {
      return console.log(event);
    }, 250));
  },
  send: function(event) {
    return console.log(event);
  }
};

I didn't try this with anything but I don't know of a reason why this wouldn't work. I have to confess to not doing much with coffeescript but it seems pretty straightforward.