Where and how to deal with events

Is there are general rule of thumb on when and where to deal with events?

In the route, controller, view?

Is there any recognized best practices around this? The guides seem kind of thin on this topic.

I think I understand the way events bubble. But wondering what should inform when to handle the event and where in the hierarchy. Particularly when having to pass messages to other controllers and parts of the system.

Another way of asking this question: what is the best way to implement something like the Cocoa FirstResponder pattern?

The FirstResponder is the first object in the responder chain that is given the opportunity to respond to an event.

Imagine a keyboard press anywhere in the app, how do you control the flow of how that key press gets translated into a semantic application event. This feels like the domain of a particular view or component. But what about events where input focus is not so clearly defined or obvious to a user?

I find myself instinctively wanting to put the event handler in a route. But uncertain about this.

I’m assuming you are talking about DOM events, like click, mousedown, etc…

Events can be on the route, especially if all views for that route need to handle the event in the same way. This also allows you to change how an event is handled based on the location in the app workflow. You can also put events on the view, but those should be specific only to that view.

If you want to do something in the controller, then you can call an action, and manipulate the data based on an event in the view that calls an action, just like the guides show. Or you can call it directly using {{action 'actionName'}} in the template.

It really depends on your use-case, and situation, but those are all valid locations.

1 Like