Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between triggers and events in backbone?

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)

like image 697
cmcculloh Avatar asked Oct 29 '12 15:10

cmcculloh


2 Answers

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/

like image 148
Derick Bailey Avatar answered Oct 03 '22 18:10

Derick Bailey


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:

  1. You want your DOM event to fire a Marionette event, instead of calling a callback function;
  2. You want your Marionette event's handler to be somewhere outside the current view, for example its parent view. In this case, this view's parent can have onChildviewAlertTitle() function to handle this alert:title event.
like image 37
Charlie Guan Avatar answered Oct 03 '22 19:10

Charlie Guan