Marionette.js. Region. CSS Animation

Shows how to configure a region to animate with CSS

by Scott Currell

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.radio/2.0.0/backbone.radio.min.js"></script>
<script src="https://rawgit.com/blikblum/backbone.marionette/refactor-region-dist/lib/backbone.marionette.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css">
<div id="main-region">
      <button class="showview" data-view="view1">Show View1</button>
      <button class="showview" data-view="view2">Show View2</button>
      <button class="showview" data-view="view3">Show View3</button>
      <button class="emptyview">Empty View</button>      
      
      <article id="content">

      </article>  
</div>

<script type="text/html" id="view-tpl">
  <h1>This is <%= name %></h1>
</script>

CSS

.view1 {
	background: #0ac2d2;
}

.view2 {
	background: #7bb7fa;
}

.view3 {
	background: #60d7a9;
}

#content {
  margin-top: 40px;
  margin-left: 10px;  
}

JavaScript

const AnimatedRegion = Mn.Region.extend({
  runShowAnimation(view) {
    let animClasses = 'animated rotateInDownRight';
    view.$el.css({display: 'block'})
      .addClass(animClasses)
      .one('animationend', function() {
        view.$el.removeClass(animClasses);        
      });
  },
  
  attachHtml(view) {    
    view.$el
      .css({display: 'none'})
      .appendTo(this.$el);      
    if (!this.isSwappingView()) this.runShowAnimation(view);
  },
  
  removeView(view) {
    let self = this; 
    view.$el.addClass('hinge animated')
      .one('animationend', function() {
        self.destroyView(view);
        if (self.currentView) self.runShowAnimation(self.currentView);
      });    
  }  
});

const ItemView = Marionette.View.extend({
  initialize(options) {
    this.model = new Backbone.Model({
      name: options.name
    })
    this.viewName = options.name;
  },
  template: "#view-tpl"
});

const MainView = Mn.View.extend({
  el: '#main-region',
  template: false,
  regions: {
    content: {
      el: '#content',
      regionClass: AnimatedRegion      
    }
  },  
  events: {
    'click .showview': 'onShowViewClick',
    'click .emptyview': 'onEmptyViewClick'
  },
  onShowViewClick: function(e) {
    var viewName = e.target.dataset.view;
    var view = new ItemView({
      name: viewName,
      className: viewName
    })
   this.showChildView('content', view);    
  },
  onEmptyViewClick: function(e) {
    this.getRegion('content').empty();    
  }
});

var mainView = new MainView();