← All examples

Custom plugin

The smallest possible plugin: it implements the SortablePlugin interface and subscribes to lifecycle events on each Sortable instance it's installed on. Drag an item to populate the log.

--:--:-- Plugin installed — waiting for drag events…

How it was wired

import { Sortable } from '../src/index.ts'

// 1. Define a plugin object that satisfies the SortablePlugin
//    interface: `name`, `version`, `install`, `uninstall`.
//    The install hook gets the Sortable instance and can subscribe
//    to its EventSystem. `eventSystem.on(...)` returns an
//    unsubscribe function — capture them for clean teardown.
const HelloPlugin = {
  name: 'Hello',
  version: '0.1.0',
  install(sortable) {
    const events = ['start', 'choose', 'move', 'sort', 'end']
    const unsubs = events.map((ev) =>
      sortable.eventSystem.on(ev, (payload) => log(ev, payload))
    )
    sortable.__helloUnsubs = unsubs
  },
  uninstall(sortable) {
    sortable.__helloUnsubs?.forEach((fn) => fn())
    delete sortable.__helloUnsubs
  },
}

// 2. Mount it globally so any Sortable can opt in.
Sortable.mount(HelloPlugin)

// 3. Create an instance and install the plugin on it.
const sortable = new Sortable(document.getElementById('cp-list'), {
  animation: 150,
  draggable: '.sortable-item',
})
sortable.usePlugin('Hello')
API summary: a plugin is any object with name, version, and install(sortable) / uninstall(sortable) methods. See docs/plugin-development.md for the full authoring guide.