简体   繁体   中英

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
    }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM