简体   繁体   English

将功能作为参数传递给coffeescript

[英]Passing function as argument in coffeescript

I'm trying to utilize the CoffeeScript Cookbook's debounce function , but I'm struggling with how to pass the function. 我正在尝试利用CoffeeScript Cookbook的debounce函数 ,但是我在如何传递该函数方面苦苦挣扎。

Here's my code: 这是我的代码:

$('#inputID').on 'keyup', =>
    query = $('#inputID').val()
    func = => console.debug(query)
    Debounce.debounceFunction func, 300, false

The debounce function is called and the 300 and the "false" are passed just fine, but the 'func' doesn't execute. 会调用debounce函数,并且可以很好地传递300和“ false”,但不会执行“ func”。

In a separate file I have: 在一个单独的文件中,我有:

root = exports ? this

class Debouncer
  debounceFunction: (func, threshold, execAsap) ->
    timeout = null
    (args...) ->
        obj = this
        delayed = ->
            func.apply(obj, args) unless execAsap
            timeout = null
        if timeout
            clearTimeout(timeout)
        else if (execAsap)
            func.apply(obj,args)
        timeout = setTimeout delayed, threshold || 100

root.Debounce = new Debouncer()

The example in the Cookbook is misleading. 《食谱》中的示例具有误导性。 You want the debouncer to return the function when registering the event handler. 您希望去抖动器在注册事件处理程序时返回该函数。 That way your timeout logic is run every time a keyup event occurs. 这样,每次发生keyup事件时,都会运行超时逻辑。

$('#inputID').on 'keyup', Debounce.debounceFunction(func, 300, false)

Try it on jsfiddle 在jsfiddle上尝试

It seems to me that with debounce you're just defining the function. 在我看来,使用反跳功能只是在定义函数。 you'll have to execute it too... 您也必须执行它...

func = ->
  query = $('#inputID').val()
  console.debug(query)

debounceFunc = debounce func, 300, false

$('#inputID').on 'keyup', -> debounceFunc()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM