简体   繁体   中英

Click event to exclude children (backbone.js)

I have 2 elements, one nested in the other. (Its a modal dialog box). When a user click the outer element, a function closeModal should be triggered, if the user click on a li within the inner elements (its children), another function like should be triggered.

Problem: I looked at other solutions and tried applying to my backbone.js View, but it does not seem to work. Is there something different that has to be changed?

View

ModalShowItemView = Backbone.View.extend({
    el: '#modal_show_item',

    events: {
        'click div#modal': 'closeModal',
        'click li#like' : 'like'
    },

    initialize: function() {
        this.render();
        this.clickHandler();
    },

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

    clickHandler: function() {
        var self = this;
        $(this.el).click(function(e) {
            if(e.target == self) {
                self.closeModal();
            }
        });
    },

    closeModal: function() {
        console.log('closemodal');
    },

    like: function() {
        console.log('like');
    }
});

Your mention of other solutions is probably what you would need to do, except on the event object itself do a .stopPropagation() as in event.stopPropagation() . I do not know that event handlers bound via delegateEvents get passed any related event object, but it's not documented on the help page AFAIK.

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