Skip to content

Instantly share code, notes, and snippets.

@tbrooke
Last active July 24, 2018 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbrooke/7be6133edc996e3799edd3bdbe40af17 to your computer and use it in GitHub Desktop.
Save tbrooke/7be6133edc996e3799edd3bdbe40af17 to your computer and use it in GitHub Desktop.
## Cocoon Docs: https://github.com/nathanvda/cocoon
Callbacks (upon insert and remove of items)
On insertion or removal the following events are triggered:
cocoon:before-insert: called before inserting a new nested child, can be canceled
cocoon:after-insert: called after inserting
cocoon:before-remove: called before removing the nested child, can be canceled
cocoon:after-remove: called after removal
To listen to the events in your JavaScript:
$('#container').on('cocoon:before-insert', function(e, insertedItem) {
// ... do something
});
...where e is the event and the second parameter is the inserted or removed item. This allows you to change markup, or add effects/animations (see example below).
## Proposed Funtion from https://stackoverflow.com/questions/12934925/cocoon-add-association-how-to-limit-number-of-associations
## Discussion on Reddit: https://www.reddit.com/r/rails/comments/5e8fca/help_how_to_limit_the_number_of_nested_fields/
$(function() {
function check_to_hide_or_show_add_link() {
if ($('#colours .nested-fields:visible').length == 5) {
$('#colours .links a').hide();
} else {
$('#colours .links a').show();
}
}
$('#colours').on('cocoon:after-insert', function() {
check_to_hide_or_show_add_link();
});
$('#colours').on('cocoon:after-remove', function() {
check_to_hide_or_show_add_link();
});
check_to_hide_or_show_add_link();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment