Anthony Kong Anthony Kong - 1 day ago 4
CoffeeScript Question

How to properly trigger default action on a bootstrap dialog?

Most of the answers on SO are either about how to activate a modal dialog box or how the dismissal works.

However what I find lacking is how to trigger an action that the default button signifies.

For example,

enter image description here

the default action of this dialog is 'Save'.

Here is the html markup

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Dialog</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btn-save" class="btn btn-primary btn-save">Save</button>
</div>
</div>
</div>
</div>


If I call
$('#myModal).modal('show')
, the dialog box will appear.

If I click on the cross on upper right corner or the 'Close' button, the dialog box will be dismissed as expected.

However, when I press 'Save', nothing happens.

I used a round-about way to implement it:

It is written in coffeescript.

$('#myModal).on('click', _.bind(@_handleSave, @))
$('#myModal).modal('show')


Then inside
_handleSave
,

_handleSaveProfile: (data) ->

return unless data.target.id is 'btn-save'
# Do saving
# ...


I don't think it is the right way because it intercepts every click event.

What is the proper to implement this function?

Answer

bind the click event to the button instead of the modal :

$('#myModal').modal('show')
$('#btn-save').on('click', _.bind(@_handleSave, @))
Comments