Usually it shouldn't trigger multiple times. It can happen however, for example when:
- Nested elements with the same class in a view. Event bubbling will cause multiple events to be fired.
- Parent views listening to click events on a class which is present in some or all children views.
An example (stripped non-relevant parts):
<script type="text/template" id="movie-list-item">
<button type="button" class="btn btn-success some-button">
<span class="some-button">Click here</span>
</button>
</script>
// Itemview
var movieItemView = Marionette.ItemView.extend({
template: "#movie-list-item",
ui: {
viewButton: '.some-button'
},
events: {
'click @ui.viewButton': 'clickHandler'
},
clickHandler: function(ev) {
// Log the click
console.log('There was a click in an itemView!');
// Uncomment the following to prevent multiple events:
//ev.stopPropagation();
}
});
// Composite view
var movieCompView = Marionette.CompositeView.extend({
template: "#movie-list",
itemView: movieItemView,
ui: {
viewButton: '.some-button'
},
events: {
'click @ui.viewButton': 'clickHandler'
},
clickHandler: function(ev) {
// Log the click
console.log('There was a click in a collectionView!');
// Uncomment the following to prevent multiple events:
//ev.stopPropagation();
}
});
Demo here: http://jsfiddle.net/Cardiff/7d3fC/2/
Note the following, if we don't use ev.stopPropagation()
in this case to prevent the event from bubbling, the console will log 4 entries; being two for the itemView and two for the collectionView. To prevent this behaviour (and you shouldn't use a click event in the collectionView in this case) and thus receive one instead of two events we use ev.stopPropagation()
.
Also keep in mind that using the ui
attribute of a view to describe the components is considered good practice and can make your life a little easier.