Two Views Sharing an Event

37 views Asked by At

I've been thrown into a Backbone code base and one of the modifications I need to make requires duplicating a text element with typeahead. Rather than copy and paste code, I'd like to re-use the event code but as I know hardly anything about Backbone I'm not sure how this should be done. Should it be a helper? If so, where do I put the helper code so it can be used by both views? I'd rather not attempt view inheritance if at all possible because I'd like to keep the changes as simple and minimal as possible.

events: {
  // all other events removed for conciseness.
  'typeahead:selected #ud_producerid': 'producerChanged'
}

I need the same event with the identical functionality in the producerChanged function as well as the setupBindings code that wires up the typeahead to work in 2 different views.

1

There are 1 answers

0
Dominic On

I know you said you didn't want to use inheritance here but it is easy in Backbone and well suited to the task.

var TypeaheadBase = Backbone.View.extend({
    events: {
         'typeahead:selected #ud_producerid': 'producerChanged'
    },

    producerChanged: function(e) {
        ...
    },

    anotherBaseMethod: function() {
        ...
    }
});

var TypeaheadBaseA = TypeaheadBase.extend({
    someOtherAMethod: function() {
        ...
    },

    // You can do some extra functionality on `producerChanged`.
    // (Or you can override by not calling the Base prototype).
    producerChanged: function() {
        TypeaheadBase.prototype.producerChanged.apply(this, arguments);
        // Do some additional stuff.
    }
});

var TypeaheadBaseB = TypeaheadBase.extend({
    // You can also extend things like events, which could be a hash (Object).
    events: function() {
        var parentEvents = _.result(TypeaheadBase.prototype, 'events');
        return _.extend({}, parentEvents, {
            'click a': 'someClickEvent'
        });
    },

    someClickEvent: function() {
        ...
    }
});