refactor this javascript code

Posted by nathanvda on Stack Overflow See other posts from Stack Overflow or by nathanvda
Published on 2012-04-06T22:54:42Z Indexed on 2012/04/06 23:29 UTC
Read the original article Hit count: 127

Filed under:
|

I have two click-events, that are nearly similar, but not quite. I am wondering how to refactor them best:

  $('.remove_fields.dynamic').live('click', function(e) {
    var $this = $(this);
    var after_removal_trigger_node = $this.closest(".nested-fields").parent();
    trigger_removal_callback($this);
    e.preventDefault();
    $this.closest(".nested-fields").remove();
    trigger_after_removal_callback(after_removal_trigger_node);
  });

  $('.remove_fields.existing').live('click', function(e) {
    var $this = $(this);
    var after_removal_trigger_node = $this.closest(".nested-fields").parent();
    trigger_removal_callback($this);
    e.preventDefault();
    $this.prev("input[type=hidden]").val("1");
    $this.closest(".nested-fields").hide();
    trigger_after_removal_callback(after_removal_trigger_node);
  });

As you can tell there is a fair bit of overlap. I am wondering what the best/nicest way would be to refactor this code.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about refactoring