Nyxynyx
Nyxynyx

Reputation: 63619

Click event not firing! (backbone.js)

I have a click handler for my View, but it seems like the view's el $('#modal') when targeted by the click event handler does not fire when clicked. But when I target any child of $('modal'), the click event is triggered on clicking.

I am guessing $('#modal') is not considered as part of the view, so click event handlers defined within events does not work on it. If so, is there another way around it?

ModalView = Backbone.View.extend({
    el: $('#modal'),

    template: _.template( $('#tpl_modal').html() ),

    events: {
        'click #modal': 'closeModal'
    },

    initialize: function() {
        _.bindAll(this, 'render', 'renderSimilarPosts', 'closeModal');
        this.render();
    },

    render: function() {
        $(this.el).fadeIn('fast').append( this.template( this.model.toJSON( this.model ) ) );
    },

    closeModal: function() {
        // some code
    }
});

Upvotes: 4

Views: 2481

Answers (1)

Austin
Austin

Reputation: 6034

instead of:

'click #modal': 'closeModal'

Try:

"click": 'closeModal'

Backbone events uses jQuery's delegate function, which applies the handler (in this case closeModal) to all children who match a given selector (in this case click #modal). Since with click #modal we are looking within #modal for a child named #modal, no elements are being found.

Take a look into delegate() to see what I mean.

Upvotes: 9

Related Questions