MarionetteJS (Backbone.Marionette) Playground

A base template to use for building Backbone and Marionette applications. http://marionettejs.com

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>Simple SelectView: Triggers event and returns model when chosen!</h1>
</header>

<article id="main">
</article>

<script type="text/html" id="sample-template">
    <div id="select1"></div>
</script>
    
<script type="text/html" id="options-template">
    <% for (i = 0; i < items.length; i++) { %>
        <option value="<%= items[i].id %>"><%= items[i].value %></option>
    <% } %>
</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.LayoutView.extend({
        template: "#sample-template",
        regions: {
            select1Region: '#select1'
        }
    });
    
    var SelectView = Marionette.ItemView.extend({
        template: "#options-template",
        tagName: "select",
        
        events: {
            'change' : 'optionSelected'
        },
        
        optionSelected: function(e){
            this.trigger('item:chosen', this.collection.get(e.target.value));
        },
    });
    
    // Define a controller to run this module
    // --------------------------------------
    
    var Controller = Marionette.Controller.extend({
        
        initialize: function(options){
            this.region = options.region
        },
        
        show: function(){
            var collection = new Backbone.Collection([
                {id: 1, value: 'Option1'},
                {id: 2, value: 'Option2'},
                {id: 3, value: 'Option3'}
            ]);
    
            var view = new MainView();
            
            var select1 = new SelectView({
                collection: collection
            });
            
            this.listenTo(select1, 'item:chosen', function(model){
                // do something with your model, e.g.
                alert('Model ID: ' + model.get('id') + ' is chosen!');
            });
            
            this.listenTo(view, 'show', function(){
                view.select1Region.show(select1);
            });
            
            this.region.show(view);
        }
        
  ...