Twitter bootstrap confirm dialog

Much time has passed since my last post. Had a lot of job… So I decided to write at least a small post. Today I share with you how I implemented analog of javascript confirm dialog using twitter bootstrap.

Nothing fancy 🙂

So let’s go. As usual I like to create base app object, that will handle common tasks – dislpay errors, keep some app data etc. And I implement it confirm function for it

$(document).ready(function() {
    window.app = {
      ...
      confirm: function(title, text, callback) {
        var confirmPopupHtml;
        confirmPopupHtml = JST['app/confirm']({
          'title': title,
          'confirm_message': text
        });
        $(window.document.body).append(confirmPopupHtml);
        $('#confirmModal').modal({});
        return $('#confirm_yes').on('click', function() {
          $('#confirmModal').modal('hide');
          return callback.call();
        });
      },
    }
    ...
})

What is interesting here – as you see I use underscore _.template function to render dialog. And i just pass callback function if user confirms the action. Javascript template is following

<!-- Modal -->
<div id="confirmModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="conrirm_label" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="conrirm_label"><%= title %></h3>
  </div>
  <div class="modal-body">
    <p><%= confirm_message %></p>
  </div>
  <div class="modal-footer">
    <button class="btn danger" id="confirm_yes">OK</button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
  </div>
</div>

And finally the example of usage.

window.app.confirm("Confirm delete", "Are you sure you want to delete selected row?", function() {
    // delete functionality
});

Leave a Reply

Your email address will not be published. Required fields are marked *