Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
});
like image 753
Nyxynyx Avatar asked Jan 17 '23 03:01

Nyxynyx


1 Answers

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.

like image 61
Austin Avatar answered Jan 19 '23 00:01

Austin