Skip to content

Instantly share code, notes, and snippets.

@armstrjare
Created June 14, 2012 00:34
Show Gist options
  • Save armstrjare/2927379 to your computer and use it in GitHub Desktop.
Save armstrjare/2927379 to your computer and use it in GitHub Desktop.
# Helper class that encapsulates common functionality of
# nested attribute fields with removal and add via a template field set.
#
# Usage:
# new NestedAttributesForm('.wrapper_for_nested_model', {
# # Additional options (see: defaultOptions)
# });
class @NestedAttributesForm
# Default options.
defaultOptions:
# Selector for any "add fields" link
addSelector: '.add-link'
# Selector for each set of nested fields
fieldsetSelector: '.fieldset'
# Selector for remove links within the fieldsets
removeSelector: '.remove-link'
# Selector for destroy field within the fieldset
destroyFieldSelector: '.destroy-field'
# Additional class on a set of fields that denotes that it is the "template" field set
templateClass: 'template'
constructor : (container, options = {}) ->
@container = $(container)
@options = $.extend({}, @defaultOptions, options)
@bindEventHandlers()
bindEventHandlers: ->
@container.delegate @options.removeSelector, 'click', (event) =>
event.preventDefault()
@removeLinkClicked(event)
false
@container.find(@options.addSelector).click (event) =>
event.preventDefault()
@addLinkClicked(event)
false
removeLinkClicked: (event) ->
fields = $(event.target).closest(@options.fieldsetSelector)
fields.find(@options.destroyFieldSelector).val("1")
fields.fadeOutSlideUp(200)
addLinkClicked: (event) ->
template = @container.find(@options.fieldsetSelector).filter(".#{@options.templateClass}")
newFields = template.clone().removeClass(@options.templateClass)
@container.find(@options.fieldsetSelector).last().before(newFields)
newFields.find('input').prop('disabled', false)
newFields.slideDownFadeIn(200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment