简体   繁体   English

如何在 Svelte 中的不同事件上触发相同的功能

[英]How to trigger same function on different events in Svelte

I have:我有:

<a href={link} on:click={() => func(param)} on:auxclick={() => func(param)}>
   click
</a>

Is there any way I can combine on:click and on:auxclick into on:click|auxclick , or something similar to this effect?有什么办法可以将on:clickon:auxclickon:click|auxclick或类似的效果吗? (Code below gives me a syntax error.) (下面的代码给我一个语法错误。)

<a href={link} on:click|auxclick={() => func(param)}>
   click
</a>

Edit: for clearer description编辑:为了更清楚的描述

You could use an action and manually set which events you want listened for:您可以使用一个操作并手动设置您想要监听的事件:

// multiClicks.js

export const multiClicks = (node, callback) => {
  node.addEventListener('click', callback)
  node.addEventListener('auxclick', callback})

  return {
    destroy() {
      node.removeEventListener('click', callback)
      node.removeEventListener('auxclick', callback})
    } 
  }
}

and then use it in your component:然后在您的组件中使用它:

<script>
  import { multiClicks } from './multiClicks.js'
</script>

<a use:multiClicks={() => func(param)}>...</a>

move your click handler in to a script tag.将您的点击处理程序移动到脚本标记中。

<script>
function handleClick(event) {
  // do something here
}
</script>

<a href={link} on:click={handleClick} on:auxclick={handleClick}>
   click
</a>

Nope, this is not possible without creating named function.不,如果不创建命名函数,这是不可能的。
And syntax you proposed: on:click|auxclick={func} is already reserved by event modifiers feature (you can learn about them from here )你提出的语法: on:click|auxclick={func}已经被事件修饰符功能保留(你可以从这里了解它们)


In the future you maybe could listen for all events - proposal and syntax could be found in issue on github将来你可能可以监听所有事件——提案和语法可以在 github 上的 issue 中找到

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

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