Search code examples
javascriptbackbone.js

How do I register an event on a backbone view element..?


I'm trying to bind a click event on the view's el itself. But I'm not able to do so.

One work around is to add an extra element around the actual view content element as the view's el.

For example, template:

<div> <!-- actual view element -->
  <div id="viewContainer"> <!-- added as dummy for event binding-->
    <div id="viewContent"></div> <!-- actual view content-->
  </div>
</div>

and register the event as:

events: {"click #viewContainer": "callback"}

Is there a way to avoid having this extra <div> and bind the events directly to view's el..?


Solution

  • To bind the events directly to view's el, just avoid the selector part of the event hash and use : {"event": "callback"} syntax

    For example, template:

      <div id="viewContent">...</div> <!-- actual view content-->
    

    and register the event as:

    events: {"click : "callback"}
    

    Backbone binds the event directly to the view's element:

    <div> <!-- actual view element-->
        <div id="viewContent"></div> <!-- actual view content-->
    </div>