search
HomeWeb Front-endJS TutorialAdvanced Stimulus: Custom Action Options

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
}

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);
});

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);
  }
}

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>

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;
});

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);
  }
}

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>

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;
});

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>

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
}

And in your HTML:

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

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
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
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 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.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment