@joystick.js/ui

Methods

How to define and use reusable methods in a Joystick component.

As your component logic grows in complexity, it can be helpful to extract reusable or verbose logic into dedicated methods. Joystick provides a methods option on your component to define arbitrary methods that are accessible from anywhere in the component via instance.methods.

Example Usage

ui/pages/index/index.js

import joystick from '@joystick.js/ui';

const Index = joystick.component({
  methods: {
    reverse_name: (name = '', instance = {}) => {
      return name?.split('')?.reverse()?.join('');
    },
  },
  events: {
    'click .reverse-name': (event = {}, instance = {}) => {
      const name = instance.DOMNode.querySelector('[name="name"]');
      const reversed_name = instance.methods.reverse_name(name.value);
      name.value = reversed_name;
    },
  },
  render: () => {
    return `
      <div>
        <form>
          <label>Name</label>
          <input type="text" name="name" placeholder="Name" />
          <button class="reverse-name">Reverse</button>
        </form>
      </div>
    `;
  },
});

export default Index;

In the example above, we've defined a method called reverse_name under the methods object. When called, Joystick passes any arguments you provide, followed by the component instance automatically.

In this case, we pass a single argument (name.value), so inside the method we receive the string as name and the instance as the second argument.

Methods can contain any logic you like—there are no expectations for return values or side effects. They're simply helper functions you can call anywhere the component instance is available.

API

Definition

methods: {
  method_name: ([...args], instance: object) => void;
}

Parameters

<method_name> function
A method defined by name on the methods object. Each method receives its passed arguments first, followed by the component instance.
instance object required
The current component instance passed as the last argument to all methods. If no arguments are passed at call time, instance will be the first (and only) argument.