Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to body click inside a view with backbone.js

I'm creating a modal dialog like this

window.NewPageModalView = Backbone.View.extend({

    template: _.template($('#view-template-new-page-dialog').html()),

    el: $('div#main'),

    events: {
        'click input[type=radio]': 'newPage'
    },

    newPage: function (event) {
        $(event.currentTarget).closest('form').submit();
    },

    initialize: function () { },

    render: function () {
        $(this.el).append(this.template());
        return this;
    }

});

and then I create it inside another view like this

addPage: function (event) {
    event.preventDefault();
    var modal = new NewPageModalView();
    modal.render();

}

this works just great but what is the best way if I want to close the dialog on body click or when pressing escape?

like image 332
marcus Avatar asked Feb 20 '23 10:02

marcus


1 Answers

Generally speaking when you bind events in backbone using the events hash they are delegated to the view's el, however you can still bind events to something else in the initialize method (in your case the body).

initialize: function() {
   $('body').bind('click', yourfunction);
 }

Edit: As @muistooshort mentions, you will want to make sure to also unbind the event.

like image 148
Jack Avatar answered Mar 06 '23 05:03

Jack