Sha256: 76951ccc0613bd7d93466327b859ea01694c76e70d128aa317acbe3929121ba8

Contents?: true

Size: 1.92 KB

Versions: 5

Compression:

Stored size: 1.92 KB

Contents

# Allows to handle a form in a modal with rails' jquery-ujs remote links and
# forms feature, without having to write any extra javascript
#
class @RemoteModalForm extends Vertebra.View
  events:
    'ajax:success form[data-remote]': 'formSuccess'
    'ajax:success a[data-remote]': 'pageLoaded'
    'ajax:error [data-remote]': 'formError'
    'hidden.bs.modal': 'modalHidden'
    'hide.bs.modal': 'modalHide'

  initialize: (options = {}) ->
    { modalMarkup, @$link, refreshOnClose } = options
    @replaceModalWith(modalMarkup)
    @refreshOnClose = if refreshOnClose? then refreshOnClose else @$link?.data('refresh-on-close')
    @trigger('shown')

  formSuccess: (e, response) ->
    @formDidSuccess = true
    @handleModalResponse(response)
    @trigger('success')

  formError: (e, jqXHR) ->
    @replaceModalWith(jqXHR.responseText)
    @trigger('error')

  pageLoaded: (e, response) ->
    @handleModalResponse(response)

  handleModalResponse: (response) ->
    if response and $.trim(response).length
      @replaceModalWith(response)
    else
      @hideModal()

  replaceModalWith: (modalMarkup) ->
    @hideModal()
    @setElement($(modalMarkup).appendTo('body').modal())
    @$el.data('remote-modal-form', this)
    @showModal()

  showModal: ->
    @$el.simpleForm?()

  hideModal: (options = {}) ->
    @$el?.modal('hide')

  modalHide: (e) ->
    @refreshPage()

  modalHidden: (e) ->
    $(e.currentTarget).remove()
    @trigger('hide')
    @trigger('close') if @$el[0] is $(e.currentTarget)[0]

  refreshPage: ->
    Turbolinks.reloadPage() if @refreshOnClose and @formDidSuccess

  trigger: (event, args...) ->
    super(event, args...)
    @$el.trigger("remote-modal-form:#{ event }", args)

# Lazy initialization when the link target is loaded
#
$(document).on 'page:change turbolinks:load', ->
  $('body').on 'ajax:success', '[data-remote-modal-form]', (e, response) ->
    new RemoteModalForm(modalMarkup: response, $link: $(e.currentTarget))

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
para-0.7.1 vendor/assets/javascripts/jquery.remote-modal-form.coffee
para-0.7.0 vendor/assets/javascripts/jquery.remote-modal-form.coffee
para-0.6.9 vendor/assets/javascripts/jquery.remote-modal-form.coffee
para-0.6.8 vendor/assets/javascripts/jquery.remote-modal-form.coffee
para-0.6.7 vendor/assets/javascripts/jquery.remote-modal-form.coffee