Marionette - on vs listenTo

Test on vs listenTo

by Gabriel Vazquez

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://underscorejs.org/underscore.js"></script>
<script src="https://backbonejs.org/backbone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.marionette/2.4.1/backbone.marionette.min.js"></script>
<header>

  <h1>A Marionette Playground</h1>

</header>
<section>
  <button id="initialize">Create</button>
  <button id="renderView">Render View</button>
  <button id="destroyHeader">Destroy</button>
</section>
<section id="app">

</section>
<section id="log">

</section>

JavaScript

// Define the app and a region to show content
// -------------------------------------------
const MainLayoutView = Marionette.LayoutView.extend({
  el: '#app',
  template: _.template('<div class="application__content"></div>'),
  regions: {
    content: '.application__content'
  }
});
const SimpleView = Marionette.ItemView.extend({
  template: _.template('<div>Simple View<button id="triggerEvent">Trigger</button></div>'),
  events: {
    'click #triggerEvent': 'triggerEvent'
  },
  triggerEvent() {
    this.trigger('event1');
  },
  onDestroy() {
    logAction('destroy view ' + this.cid);
  }
});

const ComplexLayoutView = Marionette.LayoutView.extend({
  template: _.template('LayoutView<button id="createNestedView">Create Nested View</button><div class="content"></div><div class="content2"></div>'),
  regions: {
    content: '.content',
    content2: '.content2'
  },
  events: {
    'click #createNestedView': 'createNestedView'
  },
  createNestedView: function() {
    const view2 = new SimpleView();
    this.listenTo(view2, 'event1', () => {
      logAction('this.listenTo(view2)');
      console.log('this._listenId', this._listenId);
      console.log('this._listeningTo', this._listeningTo);
    });
    logAction('create nested view ' + view2.cid);
    this.content.show(view2);
  }
});

const logAction = (message) => {
  const container = $('#log');
  container.append(message);
  container.append('<br />');
};

var MyApp = Marionette.Application.extend({
  initialize: function() {
    this.layout = new MainLayoutView();
    this.layout.render();
  }
});

const application = new MyApp();

application.on('start', (() => {
  let layout;
  $('#destroyHeader').click(() => {
    application.layout.content.empty();
  });
  $('#renderView').click(() => {
    let simpleView = new SimpleView();
    simpleView.render();
  });
  $('#initialize').click(() => {
    const complexView = new ComplexLayoutView();
    application.layout.content.show(complexView);
 ...