In Backbone Marionette, you can do extremely similar things with triggers and events:
triggers:
return Marionette.Layout.extend({
triggers: {
'click .something': 'view:handleClickSomething'
},
initialize: function(){
this.bindTo(this, 'view:handleClickSomething', this.handleClickSomething);
},
handleClickSomething: function(){}
}
vs. events:
return Marionette.Layout.extend({
events: {
'click .something': 'view:handleClickSomething'
},
handleClickSomething: function(ev){}
}
The events way seems like a quicker easier way and also makes it easier to get at the actual event itself (since it is passed in automatically). Is there a reason to use one over the other? What are their intended use cases? Having trouble finding much info about this online (other than trying to grok the annotated source)...
(I only just discovered the events method, and up until now have been using triggers for everything since I thought that was the only way)
Your first example is a bad use of triggers. Triggers are meant to be shortcuts for triggering an event from the view, so that an external object can catch the event, not the view that triggered the event.
http://lostechies.com/derickbailey/2012/05/15/workflow-in-backbone-apps-triggering-view-events-from-dom-events/
If we think both events
and triggers
as Javascript objects, then here is the difference:
Event example:
events: {
'click hi': 'alertTitle',
},
alertTitle: function () {
alert('Title!!');
}
In each event, the key ('click h1'
) is always a DOM event and a jQuery selector, the value ('alertTitle'
) is always the name of a callback function, existing inside the view.
Trigger Example:
triggers: {
'click h1': 'alert:title'
},
In each trigger, the key is still a DOM event and a jQuery selector, but the value ('alert:title'
) is always the name of a new event you want to trigger. That event handler can be defined anywhere, not necessarily inside the current view.
Trigger is helpful when:
onChildviewAlertTitle()
function to handle this alert:title
event.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With