Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone events not binding to dom element

In one of my views I have:

events: {
    'click .tab': 'doSomething',
},

then:

doSomething: function(){
    ...
},

This is a recurring structure in my views, but for some reason the 'doSomething' function is not being triggered by the click in this view.

When are the elements being bound to the event?

Any tips on debugging this?

like image 826
captDaylight Avatar asked Sep 15 '12 00:09

captDaylight


People also ask

How to bind DOM Events with the view method in backbone?

In this article, I will show you how to bind DOM events with the View method in backbone.js. At the time of writing, to use backbone.js we need to add three dependencies, the first is the "jQuery" library, the second is the "Underscore.js" library and the last is the Backbone.js library. This associates the click event to the button on the DOM.

What are the dependencies of backbone JS?

At the time of writing, to use backbone.js we need to add three dependencies, the first is the "jQuery" library, the second is the "Underscore.js" library and the last is the Backbone.js library. This associates the click event to the button on the DOM.

What happens when an element is bound to an event?

If element is bound to event, it reacts not only on action originated at itself, but also on all acts bubbled from children DOM elements. Selector parameter eliminates possible origin of event for children that satisfied it. Look at the DOM tree below:

Why do we bind events to DOM elements that do not exist?

Often it is required, or just case of convenience, to bind event to DOM elements that do not yet exist. Often, such element is generated by third party code and there is no easy way to predict when the elements are actually added to the page.


2 Answers

link to fiddle here : http://jsfiddle.net/7xRak/

Omitting the selector causes the event to be bound to the view's root element (this.el).

if your class="tab" is views DOM element means this.el then you should bind event as

events : {
  'click' : 'dosomething'
}

and for inner element in this.el like

<div class="tab">
     <span class="inner"></span>
</div>

then you should bind event as,

  events : {
      'click' : 'dosomething'
      'click .inner' : 'onInnerClick'
    }

document : http://backbonejs.org/#View-delegateEvents

like image 93
Array out of bound Avatar answered Sep 27 '22 20:09

Array out of bound


The delegation happens during the delegateEvents method at the end of the view constructor.

http://documentcloud.github.com/backbone/docs/backbone.html#section-144

Try manually calling this.delegateEvents() inside render before returning this. Are you futzing with this.el inside your initialize or render methods in a way that backbone isn't expecting?

like image 30
Peter Lyons Avatar answered Sep 27 '22 21:09

Peter Lyons