简体   繁体   English

点击事件没有开火! (Backbone.js的)

[英]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. 我的View有一个点击处理程序,但点击事件处理程序所针对的视图似乎是el $('#modal') ,点击时不会触发。 But when I target any child of $('modal') , the click event is triggered on clicking. 但是当我针对任何$('modal')孩子时,点击事件会在点击时触发。

I am guessing $('#modal') is not considered as part of the view, so click event handlers defined within events does not work on it. 我猜$('#modal')不被视为视图的一部分,所以点击中定义的事件处理程序events在这是行不通的。 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 ). Backbone事件使用jQuery的delegate函数,它将处理程序(在本例中为closeModal )应用于匹配给定选择器的所有子closeModal (在本例中click #modal )。 Since with click #modal we are looking within #modal for a child named #modal, no elements are being found. 由于click #modal我们在#modal中查找名为#modal的子项,因此没有找到任何元素。

Take a look into delegate() to see what I mean. 看看delegate()看看我的意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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