Marionette.js. Nesting Behaviors
In addition to extending a View with Behavior, a Behavior can itself use other Behaviors. The syntax is identical to that used for a View
by marionettejs
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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/css/tooltipster.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/tooltipster/3.3.0/js/jquery.tooltipster.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/marionettejs/backbone.marionette/next/lib/backbone.marionette.js"></script>
<div id="root-element">
<button class="destroy-btn tooltip">Destroy</button>
</div>
JavaScript
const { View, Behavior } = Marionette; // import { View, Behavior } from 'backbone.marionette';
const ToolTip = Behavior.extend({
options: {
content: 'Behavior content'
},
ui: {
tooltip: '.tooltip'
},
onInitialize() {
this.ui.tooltip.tooltipster({
content: this.getOption('content')
});
}
});
const DestroyWarn = Behavior.extend({
// You can set default options
// They will be overridden if you pass in an option with the same key.
options: {
message: 'You are destroying!'
},
ui: {
destroy: '.destroy-btn'
},
// Behaviors have events that are bound to the views DOM.
events: {
'click @ui.destroy': 'warnBeforeDestroy'
},
behaviors: [
{
behaviorClass: ToolTip,
content: 'Click to destroy view'
}
],
warnBeforeDestroy() {
const message = this.getOption('message');
alert(message);
// Every Behavior has a hook into the
// view that it is attached to.
this.view.destroy();
}
});
const MyView = Mn.View.extend({
el: '#root-element',
behaviors: [
{
behaviorClass: DestroyWarn,
message: 'You are about to destroy all your data!'
}
]
});
const myView = new MyView();