Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js views delegateEvents do not get bound (sometimes)

I'm using Backbone.js and sometimes the views events do not get bound correctly.

I can check the event binding situation with $(viewselector).data() in jQuery. Most of the time there are events, sometimes there aren't!

Are there any known things I should watch out for that can cause this?

like image 521
FriiSource Avatar asked Feb 26 '11 08:02

FriiSource


People also ask

What are views in Backbone JS?

In backbone. js, there are 7 modules HTTP request, Router, View, Events, Model, and Collection. Whenever a user makes a request it is directed to the router and in response to these requests, a user interface is displayed at the user end which is known as Views.

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.

Is Backbone JS frontend or backend?

Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.

What is backbone JS give its features?

Backbone. js allows developers to develop one page applications and front-end much easier and better using JavaScript functions. Backbone provides different types of building blocks like models, views, events, routers and collections for assembling client side web applications.


2 Answers

Events are delegated to this.el when the view is initialized. So you need to:

  • Create the view by giving the constructor the "el" option to specify the element
  • Define el, tag, id, classname on your view to create or find on the page your element directly.
  • Append your rendered view to the "el" element of the view
  • Make sure you do not replace the "el" element after the view creation

For the last item, if you have to do it, you can call delegateEvents once more to re-delegate the event on your view.

like image 129
2 revs, 2 users 78% Avatar answered Oct 09 '22 10:10

2 revs, 2 users 78%


My approach in these scenarios is to add delegateEvents() in render of each view that has an event, like the following:

  $(this.el).empty();
  $(this.el).html(this.template({}));
  this.delegateEvents(); // this will bind all events ONCE AGAIN

This is perfect for views specially created dynamically i.e. views that are declared new under each click or so...

like image 30
Varand Pezeshkian Avatar answered Oct 09 '22 11:10

Varand Pezeshkian