aboutsummaryrefslogtreecommitdiffstats
path: root/actionview/app/assets/javascripts/rails-ujs/features/confirm.coffee
blob: 0738ffcdc9a1f39ff8e98dbbcca8a1b8f317717d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#= require_tree ../utils

{ fire, stopEverything } = Rails

Rails.handleConfirm = (e) ->
  stopEverything(e) unless allowAction(this)

# Default confirm dialog, may be overridden with custom confirm dialog in Rails.confirm
Rails.confirm = (message, element) ->
  confirm(message)

# For 'data-confirm' attribute:
# - Fires `confirm` event
# - Shows the confirmation dialog
# - Fires the `confirm:complete` event
#
# Returns `true` if no function stops the chain and user chose yes `false` otherwise.
# Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
# Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
# return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
allowAction = (element) ->
  message = element.getAttribute('data-confirm')
  return true unless message

  answer = false
  if fire(element, 'confirm')
    try answer = Rails.confirm(message, element)
    callback = fire(element, 'confirm:complete', [answer])

  answer and callback