Search code examples
backbone.jstwitter-bootstrap-3backbone-viewsbootstrap-modal

Backbone Bootstrap modal handle close


I have bootstrap modal. Close and save I can handle with events:

    events: {
        'click #back': 'close',
        'click #save': 'save',
        'keydown': 'keyHandler'
    },

But is one problem, I cant handle when user click on .fade and close modal. How to handle this click - modal close ?


Solution

  • It's hard to tell what you are trying to accomplish because we don't see all of the code.

    It's a bad idea to simply only check for a .fade click. It's too generic and you could have another .fade somewhere else in the view. One thing could do is:

     events: {
        'click #back': 'close',
        'click .fade.modal': 'close',
        'click #save': 'save',
        'keydown': 'keyHandler'
    },
    

    This works, but this is a bad idea because if the user clicks anywhere on the modal it closes it.

    You could also listen for the close event on the modal.

    var view = Backbone.View.extend({
      events: {
            'click #back': 'close',
            'click #save': 'save',
            'keydown': 'keyHandler'
       },
      initialize: function() {
    
      },
      render: function() {
        $('#myModal').modal()
        $('#myModal').on('hidden.bs.modal', this.closeModal)
      },
      closeModal: function(){
        $('#myModal').off('hidden.bs.modal')  //prevent memory leak
        this.close()
      }
    });