Fix ChildView events with delegateEvents in onRender
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 %>.
<div class="menu"></div>
</script>
<script type="text/html" id="menu-template">
<button class="js-click-me">click me</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, $, _){
// Define a view to show
// ---------------------
var MainView = Marionette.Layout.extend({
regions: {
'menu': '.menu'
},
template: "#sample-template",
onRender: function() {
this.menu.show(this.options.menuView);
}
});
var ChildView = Marionette.ItemView.extend({
template: '#menu-template',
triggers: {
'click .js-click-me': 'clicked'
},
onClicked: function() {
alert('the button was clicked...');
},
onRender: function() {
this.delegateEvents();
}
});
// Define a controller to run this module
// --------------------------------------
var Controller = Marionette.Controller.extend({
initialize: function(options){
this.region = options.region
},
show: function(){
var model = new Backbone.Model({
contentPlacement: "here"
});
var childView = new ChildView({
model: model
});
var view = new MainView({
model: model,
menuView: childView
});
this.region.show(view);
// A 2nd render kills event listeners in the childView
// Remove this line, and it will work again...
//view.render();
}
});
// Initialize this module when the app starts
// ------------------------------------------
...