Bug Tracker

Ticket #2697 (closed bug: fixed)

Opened 7 years ago

Last modified 5 years ago

replaceWith should remove before adding

Reported by: scott.gonzalez Owned by: flesler
Priority: major Milestone: 1.4
Component: core Version: 1.4a1
Keywords: replaceWith Cc:
Blocking: Blocked by:

Description

See  Google Group post for description and possible fix.

Change History

comment:1 Changed 6 years ago by flesler

  • Owner set to flesler
  • Status changed from new to assigned

comment:2 Changed 6 years ago by snaury

I'm surprised that this bug wasn't fixed for a whole year, and I've just been affected by this.

The posting in Google Groups asks for a concrete example, and I have one. I'm creating a Rails application, where I have a _commentform template, that contains a form element, that is submitted with ajax. If there are errors in any fields, then _commentform is rerendered with error messages, and $('#formid').replaceWith('...commentform...') is used to replace old form with the new one.

Later I've added a script tag in that form, that performs some javascript on buttons on the form, using $('#buttonid'). But, unfortunately, when using .replaceWith, scripts are executed when there are *two* elements on the page with the same id, and because old form elements are before new form elements, jQuery picks old buttons (which are later removed), and now I have buttons that don't do what I'd expect.

Needless to say, that Prototype handles this situation correctly, and old elements are removed before new ones are injected, so everything works very well.

Also, I've studied jQuery sources, and it seems that using prev/after/prepend has to do a little more work than next/before/append, so perhaps this implementation would be better than the previous one:

$.fn.replaceWith = function(value) {
  return this.each(function() {
    var e = $(this);
    var s = e.next();
    var p = e.parent();
    e.remove();
    if (s.size())
      s.before(value);
    else
      p.append(value);
  });
}

comment:3 Changed 5 years ago by john

  • Status changed from assigned to closed
  • Version changed from 1.2.3 to 1.4a1
  • Resolution set to fixed
  • Milestone changed from 1.2.4 to 1.4
Note: See TracTickets for help on using tickets.