Delay (debounce) ajax request with coffeescript

你。 提交于 2020-01-05 07:52:29

问题


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.



来源:https://stackoverflow.com/questions/14000395/delay-debounce-ajax-request-with-coffeescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!