I am posting this for two reasons: First, so that I have an easy place to go when I want to start a new Backbone/Marionette application and I don’t want to search around for a bare-bones template; and second, because when I started working with Backbone/Marionette I wish I could have found something like this; the equivalent of ‘Hello World’. Code follows, with comments therein.
/* create a new instance of the Marionette app */
var app = new Backbone.Marionette.Application();
/* add the initial region which will contain the app */
app.addRegions({
/* reference to container element in the HTML file */
appRegion: '#AppBase'
});
/* define a module to keep the code modular */
app.module('App',function(module, App, Backbone, Marionette, $, _){
/* define a view; in this case a 'Layout' */
module.GardenLayoutView = Marionette.LayoutView.extend({
/* the auto-generated element which contains this view */
tagName: 'div',
/* id attribute for the auto-generated container element */
id: 'AppContainer',
/* reference to the template which will be rendered for this view */
template: '#layout-template',
/* called when the view initializes, before it displays */
initialize: function() {
console.log('initialize');
},
/* called when view renders in the DOM */
onRender: function() {
console.log('onRender');
},
/* called when the view displays in the UI */
onShow: function() {
console.log('onShow');
}
});
/* Tell the module what to do when it is done loading */
module.addInitializer(function(){
/* create a new instance of the layout from the module */
var layout = new module.GardenLayoutView();
/* display the layout in the region defined at the top of this file */
app.appRegion.show(layout);
});
});
$(document).ready(function() {app.start();});
And here is the base HTML file, including references to all of the libraries which are required for creating a Backbone/Marionette application.
<!doctype html>
<html>
<head>
<title>Backbone/Marionette bare-bones setup</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<!-- Base element for app -->
<!--
Dont use the BODY element as the base because when the app renders in the BODY
it will wipe out the template files before the views can pick them up
-->
<div id="AppBase"></div>
<!-- TEMPLATES -->
<!-- main layout template -->
<script type="text/template" id="layout-template">
<h1>This is a rendered template</h1>
</script>
<!-- libraries -->
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="js/underscore.js"></script>
<script type="text/javascript" src="js/backbone.js"></script>
<script type="text/javascript" src="js/backbone.marionette.js"></script>
<!-- app code -->
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
The libraries which load in before the code for the script can be found here:
Each link also has information necessary for learning and implementing the libraries.