Created
June 14, 2012 00:34
-
-
Save armstrjare/2927379 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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