Here’s the gist of that again:
I’ve implemented various views and objects in various manners, in order to facilitate that workflow, but what it always comes down to is that the objects facilitating the workflow need to trigger events.
A Basic Implementation
The most common way of triggering an event from a Backbone.View is to have some DOM events handled, and from the event handler/callback method for that, trigger the event you want:
This works well. I’ve done this more times than I can count. But there’s a lot of redundancy here. You can see that both of the DOM events that I’m handling have a callback method, and both of the callback methods do nothing more than trigger an event from the view itself so that the workflow can move forward.
We can do better than that… enter Marionette’s new “triggers”.
Reducing Event Triggering To Configuration
With the v0.8.2 release of Marionette, I’ve introduced the idea of view triggers – a way to configure a DOM event to trigger a view event. So instead of having to write all of that redundant code, where the only real difference is the name of the callback method and the name of the event that’s triggered, we can write this:
Must shorter. Much cleaner.
You can see that the left side of the hash is a standard Backbone.View events setup where you specify the DOM event and element selector. Then on the right hand side, specify the name of the event that you want the view to trigger when that DOM event fires. Then, when I click on the “.next” element, the view will trigger a “next” event for me. Similarly, clicking the “.previous” element will trigger a “previous” event.
Trigger From Any Marionette View
Triggers can be used from any Marionette view. You’re not limited to the ItemView type that I showed. In fact, the trigger functionality is built in to the base Backbone.Marionette.View, so even if you are creating your own specialized view type, you only need to extend from that in order to get this functionality.
Of course this isn’t a “complete” solution for handling events in your views, by any means. If you need to do anything more than trigger the event by itself, you should still use a standard event handler and callback method. At this point, there’s no way for you to configure any kind of data or objects to be passed through the event itself. But this may be added at some point in the future. I wrote this fairy quickly last night, and it suits my needs right now.
For simple scenarios where you just need to trigger an event from the view, though, this works well. I’m using it in several places where my workflow is just to display a button or a link, and have that clickable item move on to another part of the application.