Marionette.js. CollectionView's. childViewTriggers
A `childViewTriggers` hash or method permits proxying of child view events without manually setting bindings. The values of the hash should be a string of the event to trigger on the parent.
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>
<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>
JavaScript
const { View, CollectionView } = Marionette; // import { View, CollectionView } from 'backbone.marionette';
const myCollection = new Backbone.Collection([{}]);
const ChildView = View.extend({
template: _.template('<button class="button">Click me</button>'),
// Events hash defines local event handlers that in turn may call `triggerMethod`.
events: {
'click .button': 'onClickButton'
},
// Triggers hash converts DOM events directly to view events catchable on the parent.
// Note that `triggers` automatically pass the first argument as the child view.
triggers: {
'submit form': 'submit:form'
},
onClickButton() {
// Both `trigger` and `triggerMethod` events will be caught by parent.
this.trigger('show:message', 'foo');
this.triggerMethod('show:message', 'bar');
}
});
// The parent uses childViewEvents to catch the child view's custom event
const ParentView = CollectionView.extend({
collection: myCollection,
childView: ChildView,
childViewTriggers: {
'show:message': 'child:show:message',
'submit:form': 'child:submit:form'
},
onChildShowMessage: function (message) {
console.log('A child view fired show:message with ' + message);
},
onChildSubmitForm: function (childView) {
console.log('A child view fired submit:form');
}
});
const parentView = new ParentView();
parentView.render();
$('body').append(parentView.$el);