MarionetteJS - "on" vs "listenTo"

http://marionettejs.com

by Gabriel Vazquez

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script src="http://marionettejs.com/downloads/backbone.marionette.js"></script>
<header>

  <h1>A Marionette Playground</h1>

</header>
<article id="main"></article>
<script type="text/html" id="sample-template">
  put some content
  <%= contentPlacement %>.
    <button id="disposeView">Dispose View</button>
    <div id="inside-region"></div>
    <button id="appendView">Replace View</button>
</script>
<script type="text/html" id="second-template">
  second template
  <button>Trigger Event</button>
</script>

JavaScript

// Define the app and a region to show content
// -------------------------------------------

var App = new Marionette.Application();

App.addRegions({
  "mainRegion": "#main"
});

// Create a module to contain some functionality
// ---------------------------------------------

App.module("SampleModule", function(Mod, App, Backbone, Marionette, $, _) {
  var MainView = Marionette.LayoutView.extend({
    template: "#sample-template",
    regions: {
      'secondViewRegion': '#inside-region'
    },
    events: {
      "click #appendView": "appendView",
      "click #disposeView": "disposeView"
    },
    appendView: function() {
      var secondView = new SecondView();
      secondView.on('on:method:second:view', this.onSecondViewEvent.bind(this));
      //this.listenTo(secondView, 'on:method:second:view', this.onSecondViewEvent);
      this.secondViewRegion.show(secondView);
    },
    disposeView: function() {
      console.log('this', this);
      //this.secondViewRegion.reset();
      this.triggerMethod('dispose');
    },
    onSecondViewEvent: function() {
      console.log('SECOND VIEW EVENT IN MAIN');
      this.firstViewMethod();
    },
    firstViewMethod: function() {
      console.log('called');
    }
  });
  var SecondView = Marionette.ItemView.extend({
    template: "#second-template",
    events: {
      "click button": "triggerEvent"
    },
    triggerEvent: function() {
      this.triggerMethod('on:method:second:view');
    }
  });

  var Controller = Marionette.Controller.extend({

    initialize: function(options) {
      this.region = options.region;
    },

    show: function() {
      var model = new Backbone.Model({
        contentPlacement: "here"
      });

      var view = new MainView({
        model: model
      });
      
      view.on('dispose', function() {
        this.region.reset();
      }.bind(this));

      this.region.show(view);
    }

  });


  // Initialize this module when the app starts
  //...