Skip to content

Backbone and jQuery events

I have a simple task – retrieve click listener function from DOM element.

I’ve fased two problems:

  1. I have no idea how to obtain event listener, that was set via addEventListener function
  2. $(element).data('events') is always empty

Talking about first problem – I think it’s not critical as I’m using this function only in one place. But the second problem is a huge pain…

I’ve tested on pure jQuery environment:

    $(element).click(function(){})
    $(element).data('events') /*contains events info*/

But with Backbone:

    $(element).click(function(){})
    $(element).data('events') /*alway empty*/

I’m not a JS guru but it seems like there no bound data at all… Maybe it’s just a typical Backbone behaviour, but still – how can I retrieve event handler?

Answer

If you are using Backbone.js you should be managing your events inside a Backbone.View object and avoid capturing the event with JQuery directly.

You should try something like this:

var myBody  = $( 'body' );
var myDIV = $( '<DIV id="contentDIV"></DIV>' );
myBody.append( myDIV );
var myButton = $( '<button id="aButton">test</button>' );
myDIV.append ( myButton );

var MyView = Backbone.View.extend({
    el : myDIV,

    events: { 'click button#aButton' : 'doSomething' }, //here you bound the 
                                                        //event to a function.
    initialize: function(){
        _.bindAll(this, 'render') 
    },
    render: function(){
        myDIV.append('<br>working...');
    },
    doSomething: function(){
        alert( 'doSomething function.. after click event' );
    }
});

var myView = new MyView;
myView.render();

PS: A good tutorial for understanding how it works: http://arturadib.com/hello-backbonejs/