From 5047cdf0f1fb4a809c371b72a0cbb399f36f41d4 Mon Sep 17 00:00:00 2001 From: nathanvda Date: Sat, 7 Apr 2012 01:33:30 +0200 Subject: [PATCH] Pulled in the changes from erwin (pull #51)., with a few changes to clean up and maintain backwards compatibility. --- README.markdown | 5 +++++ app/assets/javascripts/cocoon.js | 16 +++++++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/README.markdown b/README.markdown index 7e1b796..235ed2a 100644 --- a/README.markdown +++ b/README.markdown @@ -220,10 +220,15 @@ $(document).ready(function() { $("#owner_from_list").show(); $("#owner a.add_fields").show(); }); + $('#owner').bind("after-removal-callback", + function() { + /* e.g. recalculate order of child items */ + }); }); ```` Do note that for the callbacks to work there has to be a surrounding container (div), where you can bind the callbacks to. +Note that the default `removal-callback` is called _before_ removing the nested item. ### Control the Insertion behaviour diff --git a/app/assets/javascripts/cocoon.js b/app/assets/javascripts/cocoon.js index e570cc6..4269926 100644 --- a/app/assets/javascripts/cocoon.js +++ b/app/assets/javascripts/cocoon.js @@ -6,7 +6,11 @@ } function trigger_removal_callback(node) { - node.parent().parent().trigger('removal-callback'); + node.trigger('removal-callback'); + } + + function trigger_after_removal_callback(node) { + node.trigger('after-removal-callback'); } $('.add_fields').live('click', function(e) { @@ -17,8 +21,6 @@ content = $this.data('template'), insertionMethod = $this.data('association-insertion-method') || $this.data('association-insertion-position') || 'before'; insertionNode = $this.data('association-insertion-node'), - insertionCallback = $this.data('insertion-callback'), - removalCallback = $this.data('removal-callback'), regexp_braced = new RegExp('\\[new_' + assoc + '\\]', 'g'), regexp_underscord = new RegExp('_new_' + assoc + '_', 'g'), new_id = new Date().getTime(), @@ -52,17 +54,21 @@ $('.remove_fields.dynamic').live('click', function(e) { var $this = $(this); - trigger_removal_callback($this); + var trigger_node = $this.closest(".nested-fields").parent(); + trigger_removal_callback(trigger_node); e.preventDefault(); $this.closest(".nested-fields").remove(); + trigger_after_removal_callback(trigger_node); }); $('.remove_fields.existing').live('click', function(e) { var $this = $(this); - trigger_removal_callback($this); + var trigger_node = $this.closest(".nested-fields").parent().parent(); + trigger_removal_callback(trigger_node); e.preventDefault(); $this.prev("input[type=hidden]").val("1"); $this.closest(".nested-fields").hide(); + trigger_after_removal_callback(trigger_node); }); })(jQuery); \ No newline at end of file