Search code examples
javascriptbackbone.jsbackbone-events

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?


Solution

  • 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.