AnApprentice
AnApprentice

Reputation: 111050

How do you bind to events using a Backbone.js view?

I'm new to backbone.js, I'm moving away from KnockoutJS. I can't get event bindings to work.

Given HTML like so:

<span id="xxxxxx">All</span>

MenuView = BB.View.extend({

    events : {
        'click #xxxxxx' : 'onNavClick'
    },

    onNavClick : function(e) {
        console.log('onNavClick');
    }
})

For some reason with the above, when I click on the span, the event is not firing. Ideas?

Thanks

Upvotes: 2

Views: 144

Answers (1)

panupan
panupan

Reputation: 1242

Try this:

MenuView = BB.View.extend({
    el: $("#xxxxxx"),

    events : {
        'click' : 'onNavClick'
    },

    onNavClick : function(e) {
        console.log('onNavClick');
    }
})

Views can manage existing dom elements if you specify which parent element it belongs to using el. You can also define views to generate html dynamically using render. Check out the todos example app, it's a good place to start.

Upvotes: 1

Related Questions