The use directive

Actions are essentially element-level lifecycle functions. They’re useful for things like:

  • interfacing with third-party libraries
  • lazy-loaded images
  • tooltips
  • adding custom event handlers

In this app, we want to make the orange box ‘pannable’. It has event handlers for the panstart, panmove and panend events, but these aren’t native DOM events. We have to dispatch them ourselves. First, import the pannable function…

  1. import { pannable } from './pannable.js';

…then use it with the element:

  1. <div class="box"
  2. use:pannable
  3. on:panstart={handlePanStart}
  4. on:panmove={handlePanMove}
  5. on:panend={handlePanEnd}
  6. style="transform: translate({$coords.x}px,{$coords.y}px)"
  7. ></div>

Open the pannable.js file. Like transition functions, an action function receives a node and some optional parameters, and returns an action object. That object can have a destroy function, which is called when the element is unmounted.

We want to fire panstart event when the user mouses down on the element, panmove events (with dx and dy properties showing how far the mouse moved) when they drag it, and panend events when they mouse up. One possible implementation looks like this:

  1. export function pannable(node) {
  2. let x;
  3. let y;
  4. function handleMousedown(event) {
  5. x = event.clientX;
  6. y = event.clientY;
  7. node.dispatchEvent(new CustomEvent('panstart', {
  8. detail: { x, y }
  9. }));
  10. window.addEventListener('mousemove', handleMousemove);
  11. window.addEventListener('mouseup', handleMouseup);
  12. }
  13. function handleMousemove(event) {
  14. const dx = event.clientX - x;
  15. const dy = event.clientY - y;
  16. x = event.clientX;
  17. y = event.clientY;
  18. node.dispatchEvent(new CustomEvent('panmove', {
  19. detail: { x, y, dx, dy }
  20. }));
  21. }
  22. function handleMouseup(event) {
  23. x = event.clientX;
  24. y = event.clientY;
  25. node.dispatchEvent(new CustomEvent('panend', {
  26. detail: { x, y }
  27. }));
  28. window.removeEventListener('mousemove', handleMousemove);
  29. window.removeEventListener('mouseup', handleMouseup);
  30. }
  31. node.addEventListener('mousedown', handleMousedown);
  32. return {
  33. destroy() {
  34. node.removeEventListener('mousedown', handleMousedown);
  35. }
  36. };
  37. }

Update the pannable function and try moving the box around.

This implementation is for demonstration purposes — a more complete one would also consider touch events.