It's because the registering on
is done multiple times, somewhere not shown in your question, and it should only be done once.
✘ Don't do this
var view = Backbone.View.extend({
events: {
"click": "onClick"
},
onClick: function(e) {
App.actionsChannel.on('action:triggered', function(actionName) {
//do some ajax requests
});
}
});
✔ Do this
var view = Backbone.View.extend({
events: {
"click": "onClick"
},
initialize: function(){
App.actionsChannel.on('action:triggered', this.onActionTriggered);
},
onClick: function(e) {
// or if you must register it here for example.
// First make sure it's unregistered.
App.actionsChannel.off('action:triggered', this.onActionTriggered);
App.actionsChannel.on('action:triggered', this.onActionTriggered);
},
onActionTriggered: function(actionName) {
//do some ajax requests
},
});
Using the on
function multiple times just adds another listener to the list. So, when triggered, the callback is called as much times as it was registered.
The best
It is recommended to use listenTo
instead of on
whenever possible to avoid memory leaks.
Backbone.js on
vs listenTo
var view = Backbone.View.extend({
events: {
"click": "onClick"
},
initialize: function(){
// this will be removed automatically when the view is `remove`d,
// avoiding memory leaks.
this.listenTo(App.actionsChannel, 'action:triggered', this.onActionTriggered);
},
onClick: function(e) {
},
onActionTriggered: function(actionName) {
//do some ajax requests
},
});
The code snippets above are just examples of how to listen to an event. Use trigger
where you need it and where it make sense.