Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delegateEvents in backbone.js

Can anyone please explain me what delegateEvents in backbone.js does? The documentation did not help me to understand.

My exact use case is:

I have a main view X with an inner view Y. They work great, but if I go to main view Z and then go back to X (reusing, not recreating) then events attached to Y child elements get lost. delegateEvents solves this but I want to understand why.

like image 624
Yaron Naveh Avatar asked Jun 17 '12 18:06

Yaron Naveh


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

What is module in Backbone JS?

js respectively. The rest of your application code should be divided into modules that can live under their own modules directory. A module is an encapsulated group of structures (for the purposes of our post, Backbone structures) that work cohesively to provide a subset of functionality in your application.

Is Backbone JS frontend or backend?

Front-End MVC frameworks (Backbone, Angular, etc) all rely on a backend service to provide the data that, say Backbone, would then use as its model. You could have an entire MVC pattern on the backend that accepts requests and spits out some JSON for a frontend MVC framework to use.


1 Answers

Essentially, when you call .remove() it is a proxy to the jQuery remove function, which removes the element from the DOM, as well as all associated events from the event hash that were bound to the element.

Backbone's View element still contains the .el, but upon re-inserting in the DOM, the jQuery element has lost all of it's bound listeners.

There are a few solutions:

  1. Completely destroy the view element, including unbinding all model/controller events with the new destroy method (currently only in the github, it will be added in the next release of Backbone) and create a new view when coming back (rather than just caching and re-rendering) - my preferred method

  2. Create a method (or extend remove) to use jQuery's detatch which apparently does the same as remove without losing the event bindings - haven't done it but seems like it would work

  3. Call .delegateEvents() in every render - what you're currently doing now

Hope this helps.

like image 58
tgriesser Avatar answered Oct 08 '22 22:10

tgriesser