Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone: add event listener only if doesn't already exist

In other words: how do I find list of events already being listened to?

I'm using Backbone.on(... and Backbone.trigger(... to communicate between two Views that don't know about each other. However, the View that adds the listener is really an "item-view" for a collection and so I get many listeners added, and so I want to first check if that event is already being listened to. 10x.

like image 226
yar1 Avatar asked Jan 17 '13 11:01

yar1


Video Answer


1 Answers

The Backbone.Events object has a dictionary of events called _events

So to check if some event is already being listened to you could for example implement a function in the view in question:

isEventListenedTo: function(eventName) {
  return (view._events) ? !!view._events[eventName] : false;
}

The _events -dictionary contains arrays for each eventname so you could also check for how many times the event is listened to etc.

Hope this helps!

like image 136
jakee Avatar answered Oct 02 '22 19:10

jakee