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 Layout</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 Event</button></div>'),
events: {
'click #triggerEvent': 'triggerEvent'
},
triggerEvent() {
this.trigger('event1');
},
onDestroy() {
console.log('destroy view ' + this.cid);
}
});
const ComplexLayoutView = Marionette.LayoutView.extend({
template: _.template('LayoutView' +
'<button id="createNestedView">Create Nested this.listenTo</button>' +
'<button id="createNestedView2">Create Nested view.listenTo</button>' +
'<div class="content"></div><div class="content2"></div>'),
regions: {
content: '.content',
content2: '.content2'
},
events: {
'click #createNestedView': 'createNestedView',
'click #createNestedView2': 'createNestedView2'
},
createNestedView: function() {
const view2 = new SimpleView();
this.listenTo(view2, 'event1', () => {
console.log('this.listenTo(view2)');
this.logListeners();
});
// view2.on('destroy', () => { this.stopListening(view2) });
console.log('create nested view ' + view2.cid);
this.content.show(view2);
},
createNestedView2: function() {
const view2 = new SimpleView();
view2.listenTo(view2, 'event1', () => {
console.log('view2.listenTo(view2)');
this.logListeners();
});
console.log('create nested view ' + view2.cid);
this.content.show(view2);
},
logListeners: function() {
console.log('Layout - this._listenId', this._listenId);
console.log('Layout - this._listeningTo', this._listeningTo);
},
onDestroy: function() {
this.logListeners();
}
});
var MyApp =...