20

I am using Backbone and I have a view with events defined:

    ....
    events: {
        'click .search-button': 'setModelTerm',
        'change .source-select': 'setModelSourceId',
        'change .source-select': 'activateSource'
    },
    ....

I would like to trigger two methods when the event change .source-select fires. The problem is that the last entry in the event object overrides the preceding entry.
How can I trigger two methods in one event?
(I am trying to prevent writing another method that calls those two methods)

4

3 回答 3

42

You can pass a wrapper function in your hash of events to call your two methods.

From http://backbonejs.org/#View-delegateEvents

Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body.

Try

events: {
    'click .search-button': 'setModelTerm',
    'change .source-select': function(e) {
        this.setModelSourceId(e);
        this.activateSource(e);
    }
},
于 2012-11-13T15:57:53.157 回答
7

The only thing that is keeping you from adding the same event/selector pair is that events is a hash - jQuery can handle multiple bindings to the same element/event pair. Good news though, jQuery events allow you to namespace events by adding a .myNamespace suffix. Practically speaking, this produces the same results but you can generate many different keys.

var MyView = Backbone.View.extend({
  events: {
    'click.a .foo': 'doSomething',
    'click.b .foo': 'doSomethingElse'
    'click.c .foo': 'doAnotherThing', // you can choose any namespace as they are pretty much transparent.
  },

  doSomething: function() {
    // ...
  },

  doSomethingElse: function() {
    // ...
  },

  doAnotherThing: function() {
    // ...
  },
});
于 2016-04-20T16:56:51.060 回答
1

The events hash in your view is just a convenience "DSL" of sorts. Just bind your 2nd event manually inside initialize.

events: {
    'click .search-button': 'setModelTerm'
},
initialize: function () {
    _.bindAll(this);
    this.on('click .search-button', this.doAnotherThing);
}
于 2012-11-13T15:42:54.410 回答