Search code examples
javascripteventsdombackbone.js

Stopping listening to DOM events in Backbone


Today I learned that the listenTo method of Backbone.View is intended for listening for events trigger-ed by changes in Backbone models or collections. It is not designed to listen to DOM events.

Which raises the following question. Backbone documentation says that when a Backbone view is remove-ed, it will automatically unsubscribe from all events that it was listening through listenTo. It does not specifically mention the fate of the listeners that the view placed on the DOM elements.

So what happens when a view listenining to DOM events is being removed? And is there any difference between the following two scenarios?

  • a view has an events object that contains a list of events on the child nodes of the view’s $el that are being listened to;

  • a view listens to some arbitrary DOM elements, not necessarily children of the view’s $el. is this situation any different from the previous one?

Will the view’s listeners unsubscribe from the DOM events automatically when the view is removed or should they be unsubscribed manually?


Solution

  • a view has an events object that contains a list of events on the child nodes of the view’s $el that are being listened to;

    These will be undelegated (removed) by backbone when view is removed properly using it's remove method.

    a view listens to some arbitrary DOM elements, not necessarily children of the view’s $el. is this situation any different from the previous one?

    There is no built in way of doing this using backbone, and is not recommended. If you do this by yourself - Some element holding event listeners pointing to methods on your view which backbone is not aware of - You have to clean these up yourself else it'll create zombie views (memory leaks)