Home Web Front-end JS Tutorial Advanced Stimulus: Custom Action Options

Advanced Stimulus: Custom Action Options

Dec 06, 2024 pm 10:18 PM

Advanced Stimulus: Custom Action Options

This article was originally published on Rails Designer


Stimulus allows you to register your own custom action options. These are the things you can append to an action, like keypress->input#validate:prevent (as shown in the article on Stimulus Features You (Didn't) Know). :prevent is an action option and will prevent the default event. Other available options are: :stop, and :self.

You can create your own as well! Allowing you to squeeze even more out of Stimulus (who would've thought a modest framework had some many feature?!).

I want to list a few suggestions to help you get an idea of what they can do and inspire you to make your own.

The basics

You can create your own action options with the Application.registerActionOption method. The method would then either return true or false, based on the logic you added.

The basics look like this:

// app/javascript/controllers/application.js
import { Application } from "@hotwired/stimulus"

const application = Application.start()

application.registerActionOption("fire", ({ event, value }) => {
  // any logic that returns true/false
}
Copy after login
Copy after login

When it returns true, the action it is appended to, would run. Used like this: click->controller#action:fire.

Now the basics are clear, let's look at some examples on how you could use it.

WhenOutside

A common action is to click outside of an element to hide it, for example with modals or dropdowns. Logic would be something like this:

application.registerActionOption("whenOutside", ({ event, element }) => {
  return !element.contains(event.target);
});
Copy after login
Copy after login

And your Stimulus controller could look like this:

// app/javascript/controllers/dropdown_controller.js
import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["menu"];

  show() {
    this.menuTarget.removeAttribute("hidden");
  }

  hide() {
    this.menuTarget.setAttribute("hidden", true);
  }
}
Copy after login

Then in your HTML:

<div data-controller="dropdown">
  <button data-action="dropdown#show:stop">Show</button>

  <ul data-dropdown-target="menu" data-action="click@window->dropdown#hide:whenOutside">
  </ul>
</div>
Copy after login

Only when you click outside the ul with data-dropdown-target="menu" will it hide the target. Did you notice the :stop action option? I've explored it in the article on Stimulus Features You (Didn't) Know.

Throttled

Now assume your dropdown_controller.js has a toggle method and you only want your users to toggle it every 1000ms for whatever reason (no judgement!).

const throttles = new WeakMap();

application.registerActionOption("throttled", ({ element }, { wait = 1000 } = {}) => {
  if (!throttless.has(element)) {
    throttles.set(element, 0);
  }

  const now = Date.now();
  const lastRun = throttles.get(element);

  if (now - lastRun >= wait) {
    throttles.set(element, now);

    return true;
  }

  return false;
});

Copy after login

This will only return true once every 1000ms.

? WeakMap? WTF?! I am working on a book so it's less scary! Pre-order JavaScript for Rails Developers.

Let's extend the dropdown_controller.js with a toggle method:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["menu"];

  show() {
    this.menuTarget.removeAttribute("hidden");
  }

  toggle() {
    this.menuTarget.toggleAttribute("hidden");
  }

  hide() {
    this.menuTarget.setAttribute("hidden", true);
  }
}

Copy after login

Use it like this:

<div data-controller="dropdown">
  <button data-action="dropdown#show:stop:throttled">Show</button>

  <ul data-dropdown-target="menu" data-action="click@window->dropdown#hide:whenOutside">
  </ul>
</div>
Copy after login

See how it's possible to stack action options? Both stop and throttled are used.

WithMetakey

Another example could be when you only want to open the dropdown when the meta () or ctrl key is pressed

application.registerActionOption("withMetaKey", ({ event }) => {
  return event.metaKey;
});
Copy after login

Use it in your HTML like so:

<div data-controller="dropdown">
  <button data-action="dropdown#show:stop:throttled:withMetaKey">Show</button>

  <ul hidden data-clicker-target="menu" data-action="click@window->dropdown#hide:whenOutside">
    <li>Menu Item</li>
  </ul>
</div>
Copy after login

The dropdown will only be shown whenever cmd/ctrl is pressed too when clicking.

One more? One more!

WithConfirm

Want to show a confirm dialog before you show the dropdown?

// app/javascript/controllers/application.js
import { Application } from "@hotwired/stimulus"

const application = Application.start()

application.registerActionOption("fire", ({ event, value }) => {
  // any logic that returns true/false
}
Copy after login
Copy after login

And in your HTML:

application.registerActionOption("whenOutside", ({ event, element }) => {
  return !element.contains(event.target);
});
Copy after login
Copy after login

And all these stacked custom actions will work! For the given example not practical use, but it shows all the things you can do with them.

As you noticed, I like to name the custom action options so they make it easy to understand when read in the action:

  • click@window->dropdown#hide:whenOutside;
  • click->dropdown#show:withMetakey.

Personal preference. You can of course name them however you want.

For lots of these example would you normally need to create separate actions, but not with custom action options. Once you've seen them in use, you will find plenty of use cases for them.

? I have collected these custom action options in a small, tidy package called stimulus-fx; be sure to check it out! Do contribute if you find it useful!

The above is the detailed content of Advanced Stimulus: Custom Action Options. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles