hotwired / stimulus

A modest JavaScript framework for the HTML you already have

Home Page:https://stimulus.hotwired.dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Proposal: Default controller action

pythonandchips opened this issue · comments

Hi,

It would be great to be able to define a default method for an action on a controller so that only have one define the event and controller, or just the controller for an action.

So for example

class LogController extends Controller {
  static defaultAction = "log"

  log() {
    // do something interesting
  } 
}
<a data-action="click->log">Log</a>

an alternative could be having a reserved action name that stimulus uses if the method name is not in the action descriptor e.g.

class LogController extends Controller {
  _() {
    // do something interesting
  } 
}
<a data-action="click->log">Log</a>

We have quite a lot of small, reusable single action controllers and this could simplify adding actions and make it a bit more economical.

I'd be happy to give it a go if folk like the idea and someone could give me a pointer on how to run a single test 😄

I'd recommend you look at the Stimulus use library - it's got a nice approach to abstract common behaviour.

https://github.com/stimulus-use/stimulus-use

Additionally, you could just use class inheritance of something like your common BaseController that contains the shared behaviour.

Finally, for logging specifically, just a reminder you can use the debug mode. https://stimulus.hotwired.dev/handbook/installing#debugging

And you can throw errors in your controller code and leverage the onerror code - https://stimulus.hotwired.dev/handbook/installing#error-handling

@lb- Cheers for the reply, the log controller above was just an example, what I am proposing is making it easier to use controller with a single method by defining a default method for the controller, ether by specificing the name of the action or using _ as the method name.

In our app we have lots of controller that have just a single action. Some of these are, generic controllers like sumbitting a form on change or input, refreshing a turbo frame from an action other are specific to our application.

Sorry if my initial post wasn't clear.