Alex Rivera | Logout

Delegating events to a parent view in Backbone

Asked 2012-05-07T16:25:47.407
9

My view, TuneBook, has several child views of type ClosedTune. I also have separate full page views for each tune, OpenTune. The same events are bound within ClosedTune and OpenTune, so I've designed my app so that they both inherit from a shared 'abstract' view Tune.

To make my app more scaleable I would like the events for each ClosedTune to be delegated to TuneBook, but for maintainability I would like the same handlers (the ones stored in Tune) to be used by TuneBook (although they'd obviously need to be wrapped in some function).

The problem I have is, within TuneBook, finding the correct ClosedTune to call the handler on. What's a good way to architect this, or are there other good solutions for delegating events to a parent view?

Note - not a duplicate of Backbone View: Inherit and extend events from parent (which is about children inheriting from a parent class, whereas I'm asking about children which are child nodes of the parent in the DOM)

Edit
Report

1 Answer

7

Here are a couple of possibilities.

1. Centralized: store ClosedTune objects in the TuneBook instance

  1. Store a reference to each ClosedTune in tune_book.tunes. How you populate tune_book.tunes is up to you; since you mentioned an adder method on TuneBook, that's what I've illustrated below.

  2. In the TuneBook event handler, retrieve the ClosedTune from tune_book.tunes by using something like the id attribute of the event target as the key. Then call the Tune or ClosedTune handler.

http://jsfiddle.net/p5QMT/1/

var Tune = Backbone.View.extend({
  className: "tune",

  click_handler: function (event) {
    event.preventDefault();
    console.log(this.id + " clicked");
  },

  render: function () {
    this.$el.html(
      '<a href="" class="button">' + this.id + '</a>'
    );

    return this;
  }
});

var ClosedTune = Tune.extend({});

var OpenTune = Tune.extend({
  events: {
    "click .button" : 'click_handler'
  }
});

var TuneBook = Backbone.View.extend({
  events: {
    "click .tune .button" : 'click_handler'
  },

  click_handler: function (event) {
    var tune = this.options.tunes[
      $(event.target).closest(".tune").attr('id')
    ];

    tune.click_handler( event );
  },

  add_tune: function (tune) {
    this.options.tunes[tune.id] = tune;
    this.$el.append(tune.render().el);
  },

  render: function () {
    $("body").append(this.el);
    return this;
  }
});

var tune_book = new TuneBook({
  tunes: {}
});

[1, 2, 3].forEach(function (number) {
  tune_book.add_tune(new ClosedTune({
    id: "closed-tune-" + number
  }));
});

tune_book.render();

var open_tune = new OpenTune({
  id: "open-tune-1"
});

$("body").append(open_tune.render().el);
answered 2012-05-07T17:42:14.267

Your Answer