简体   繁体   中英

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)

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:

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM