nathanvda
nathanvda

Reputation: 50057

refactor this javascript code

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.

Upvotes: 1

Views: 299

Answers (3)

Joseph
Joseph

Reputation: 119837

taking cleaning a bit more:

$('.remove_fields').click(function(e) {
    e.preventDefault();

    var $this = $(this);
    var $nestedFields = $this.closest(".nested-fields");

    trigger_removal_callback($this);

    if($this.hasClass("dynamic") {
        $nestedFields.remove();
    } else if($this.hasClass("existing")) {
        $this.prev("input[type=hidden]").val("1");
        $nestedFields.hide();
    }

    trigger_after_removal_callback($nestedFields.parent());

});

Upvotes: 1

Elliot Bonneville
Elliot Bonneville

Reputation: 53301

Do a class check in the .remove_fields click function.

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

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Combine the selectors into $('.remove_fields.dynamic, .remove_fields.existing').

Then, test if $this has class existing. If so, run $this.prev("input[type=hidden]").val("1");.

Done.

Upvotes: 3

Related Questions