You can delegate events by on:* 🎉

Overview

NPM license NPM version Code Style: Prettier Build Status Coverage Status

Delegate events with on:* 🎉

  • 💡 Easy to use
  • ⚡️ No performance impact
  • 🔑 No type errors with svelte-check

Try it on Stackblitz 🚀.

Overview

Since 2019, one popular issue on the Svelte GitHub repository has been delegating all events.
sveltejs/svelte#2837

This repository aims to solve this issue.

Example

Component.svelte

<!-- Delegate all events with `on:*` 🎉 -->
<input on:* />

App.svelte

<script>
  import Component from './Component.svelte';
</script>

<!-- Handle events as desired -->
<Component
  on:input="{(e) => console.log(e.target.value)}"
  on:blur="{() => console.log('blur')}"
/>

Installation

npm install -D svelte-preprocess-delegate-events

Usage

After installation, add this as a Svelte preprocessor.

// svelte.config.js
import delegateEvents from "svelte-preprocess-delegate-events/preprocess";

const config = {
  // Add this preprocessor at the end of the array.
  preprocess: [delegateEvents()],
};

export default config;

Integration with svelte-check

If you want to use svelte-check, create svelte-jsx.d.ts at the project root and update [tj]sconfig.json.

svelte-jsx.d.ts

declare namespace svelteHTML {
  /**
   * base: https://github.com/sveltejs/language-tools/blob/651db67858d18ace44d000d263ac57ed5590ea05/packages/svelte2tsx/svelte-jsx.d.ts#L42
   */
  type HTMLProps<Property extends string, Override> =
    Omit<
      Omit<import('svelte/elements').SvelteHTMLElements[Property], keyof EventsWithColon<Omit<svelte.JSX.IntrinsicElements[Property & string], svelte.JSX.AttributeNames>>> & EventsWithColon<Omit<svelte.JSX.IntrinsicElements[Property & string], svelte.JSX.AttributeNames>>,
      keyof Override
    > & Override & (Record<'on:*', (event: Event & { currentTarget: EventTarget & EventTarget }) => any | never> | object);
}

[tj]sconfig.json

{
+ "include": ["./svelte-jsx.d.ts"]
}

How the Preprocessor Works?

This chapter explains how the preprocessor functions. The preprocessor operates differently for Elements and Components.

Element

Consider the following simple example:

<!-- Parant.svelte -->
<script>
  import Child from './Child.svelte';
</script>
<Child on:click={() => console.log('clicked!')} />

<!-- Child.svelte -->
<button on:*>Click Me</button>

Svelte executes events registered in component.$$.callbacks when an event is triggered in a child component. In the example above, component.$$.callbacks is as follows:

component.$$.callbacks = {
  click: () => console.log('clicked!')
}

This preprocessor adds a process to listen for events registered in component.$$.callbacks for elements with on:*. After preprocessing, Child.svelte looks like this:

<!-- Child.svelte -->
<script>
  import { boundElements, registerDelegatedEvents } from 'svelte-preprocess-delegate-events/runtime';
  import { get_current_component } from 'svelte/internal';
  let button = boundElements();
  const component = get_current_component();
  $: registerDelegatedEvents(button.bounds, component, (handler) => handler, {});
</script>

<button bind:this={button.bounds}>Click Me</button>

NOTE: The reason for binding <button> to button.bounds instead of binding it to the button variable is to support cases where multiple elements exist, such as <button> in a {#each} block.

In this way, only events that are being listened to by the parent component are listened to, thus providing a mechanism with no performance overhead.

Component

Component uses a different mechanism than Element. Consider the following simple example:

<!-- Parant.svelte -->
<script>
  import Child from './Child.svelte';
</script>
<Child on:click={() => console.log('clicked!')} />

<!-- Child.svelte -->
<script>
  import GrandChild from './GrandChild.svelte';
</script>
<GrandChild on:* />

<!-- GrandChild.svelte -->
<button on:click on:blur>Click Me</button>

If you are using on:* in Child.svelte, you need to forward all events from GrandChild to Parent. However, Child does not know what events are coming from GrandChild, so you need to do something. Specifically, when GrandChild triggers an event, it will refer to component.$$.callbacks to run its event handlers. By proxying component.$$.callbacks, you will know which events have been forwarded. Forwarded events can be communicated to the parent component so that the Parent component can handle the event.

After preprocessing, it looks like this:

<!-- Child.svelte -->
<script>
  import { boundComponents, proxyCallbacks } from 'svelte-preprocess-delegate-events/runtime';
  import { get_current_component } from 'svelte/internal';
  import GrandChild from './GrandChild.svelte';

  const GrandChild = boundComponents();
  const component = get_current_component();
  $: proxyCallbacks(component, GrandChild.bounds, false);
  </script>

<GrandChild bind:this={GrandChild.bounds} />

Note

on:* does not support specifying event handlers directly because a useful use case could not be found. If you have a useful use case, please create a new issue.

<script>
  import Component from './Component.svelte';
  const handleEvent = (e) => {
    console.log(e);
  }
</script>

<!-- Specifying event handler directly is not supported -->
<input on:*="{handleEvent}" />

<!-- Specifying event handler directly is not supported -->
<Component on:*="{handleEvent}" />
Comments
Releases(v0.4.1)
Owner
Yuichiro Yamashita
Yuichiro Yamashita
This is a project that is used to execute python codes in the web page. You can install and use it in django projects, You can do any operations that can be performed in python shell with this package.

Django execute code This is a project that is used to execute python codes in the web page. You can install and use it in django projects, You can do

Shinu 5 Nov 12, 2022
A full stack mern application called "memories" where users can post interesting events occurring in their life

Memories App ?? ?? ?? Live Demo ?? ?? ?? Full Stack "R"ERN Application - from start to finish. The App is called "Memories" and it is a simple social

Phenom 7 Sep 24, 2022
The website which can help you to organize your daily or weekly activities and review them when you need them. you can add, remove and delete an activity

To Do list To do project is webpack project that list activities someone can do at a specific time In this TO-DO list, you can add or remove you activ

Joffrey NKESHIMANA 5 Jul 21, 2022
Event scheduler is a simple app for viewing the events happening around you

Event scheduler is a simple app for viewing the events happening around you. User can also create their event and include a location. Location can also be marked as hidden(strictly by IV). Built with React and Styled Components

Anselem Odimegwu 3 Mar 29, 2022
A jQuery plugin that lets you attach callbacks to useful image loading events.

waitForImages Copyright (c) 2011-2018 Alexander Dickson @alexdickson Licensed under the MIT licenses. http://alexanderdickson.com Donate! Overview Pro

Alexander Dickson 1.3k Dec 28, 2022
DoMe is a ToDo App. you can add, delete and reorder elements of the todo list using drag and drop. You can also toggle between dark&light mode

DO ME Todo App Live Preview : DO ME Built With : - ReactJS - TailwindCSS Make sure you have: - Git - Nodejs version 14 or higher (we recommend using

Medjahdi Islem 5 Nov 18, 2022
This is a simple web application of a To-do List in which you can add, remove and edit all your tasks and also you can mark each task as completed and delete all completed ones.

To-Do List A simple web application of a to do list Built With HTML, CSS, JS, ES6 & Webpack Getting Started In this repository I created To-Do List SP

Juan Sebastian Sotomayor 12 Apr 11, 2022
Adds `swiped` events to the DOM in 0.7k of pure JavaScript

swiped-events A 0.7k script that adds swiped-left, swiped-right, swiped-up and swiped-down events to the DOM using CustomEvent and pure JS. Based on t

John Doherty 493 Jan 8, 2023
AppRun is a JavaScript library for developing high-performance and reliable web applications using the elm inspired architecture, events and components.

AppRun AppRun is a JavaScript library for building reliable, high-performance web applications using the Elm-inspired architecture, events, and compon

Yiyi Sun 1.1k Dec 20, 2022
Web Gesture Events

Web Gesture Events A library that brings high-level asynchronous gesture events to the web by extending the standard addEventListener interface. ☝?? ?

Nathan Johnson 7 May 29, 2022
Integrate Railway Project events with Telegram Chat/Channel using Railway Webhooks

Railway to Telegram Integrate Railway Project events with Telegram Chat/Channel using Railway Webhooks! One Click Self Deploy Manual Self Deploy Fork

Agampreet Singh 9 Jul 5, 2022
Timers for Lost Ark bosses, islands, events, wandering merchants and more! Never miss an event again.

Timers for Lost Ark bosses, islands, events, wandering merchants and more! Never miss an event again. LostArkTimer.app Website Website Features Event

Joshua Kuan 28 Oct 17, 2022
It's the ragemp server middlewares for events

RageMP Server Middlewares Данный пример промежуточных функций разработан, чтобы любые другие разработчики могли им пользоваться. Документация: App App

null 8 Sep 8, 2022
An open-source analytics library to measure user events the hassle-free way.

walker.js The walker.js is an open-source event tracker for all tools. Easy, standardized & flexible. Capture user events in the browser by setting HT

elbwalker 181 Dec 22, 2022
A JavaScript library for adding ripple effects to HTML elements based on mouse events.

About project Ripplejs is an open source javascript library created for the purpose of adding ripple effects to html elements based on mouse events. L

Udezue Oluomachi Chimaobi 7 May 10, 2022
A project for experimenting with Server Sent Events (SSE), a way of communication going from server to client.

A project for experimenting with Server Sent Events (SSE), a way of communication going from server to client.

Italo Menezes 4 May 16, 2022
NFC based attendance recording app for offline events.

NFC Entry NFC based attendance recording app for offline events. Capture proof of presence in offline events using NFC enabled ID Cards and a smartpho

Vaibhav Garg 9 Sep 24, 2022