如何使用 Svelte 去抖动/节流?

How to debounce / throttle with Svelte?

所以我目前有:

App.html

<div>
  <input on:input="debounce(handleInput, 300)">
</div>

<script>
  import { debounce } from 'lodash'

  export default {
    data () {
      name: ''
    },

    methods: {
      debounce,
      async handleInput (event) {
        this.set({ name: await apiCall(event.target.value).response.name })
      }
    }
  }
</script>

并得到错误 Uncaught TypeError: Expected a function at App.debounce。这来自 Lodash,因此似乎没有通过 Svelte 的方法。

额外额外编辑

关于我目前如何实现它的额外背景:

oncreate () {
  const debounceFnc = this.handleInput.bind(this)

  this.refs.search.addEventListener('input', debounce(debounceFnc, 300))
}

应该去抖的是方法本身——因此与其在每个输入事件上调用 debounce,不如将 handleInput 设置为去抖方法:

<div>
  <input on:input="handleInput(event)">
</div>

<script>
  import { debounce } from 'lodash'

  export default {
    data () {
      return { name: '' };
    },

    methods: {
      handleInput: debounce (async function (event) {
        this.set({ name: await apiCall(event.target.value).response.name })
      }, 300)
    }
  }
</script>

Simplified REPL example here.

编辑:svelte v3 版本

<input on:input={handleInput}>

<script>
  import debounce from 'lodash/debounce'

  let name = '';

  const handleInput = debounce(e => {
    name = e.target.value;
  }, 300)
</script>

REPL example here.

接受的答案对 Svelte v1 有效。对于 v3,您可以使用此代码实现相同的目的:

<input placeholder='edit me' bind:this={input}>
<p>name: {name}</p>

<script>
  import { onMount } from "svelte"
    import { debounce } from 'lodash-es'
    var name="", input;
    onMount(()=>{
        input.addEventListener('input', debounce((e)=>{name=e.target.value}, 250))
    })
</script>