Element reference breaks on modification of innerHTML property of container

后端 未结 2 1037
[愿得一人]
[愿得一人] 2021-01-20 00:15

When creating elements via code, I have encountered an issue where modifying the innerHTML property of an element breaks any references to other elements that a

2条回答
  •  面向向阳花
    2021-01-20 01:03

    few things here.

    first of all. strings are immutable hence doing element.innerHTML += "
    "
    acts as a complete read and rewrite.

    second, why that is bad:

    aside from performance, mootools (and jquery, for that matter) assigns special unique sequential uids to all referenced elements. you reference an element by calling a selector on it or creating it etc.

    then consider that SPECIFIC element with uid say 5. the uid is linked to a special object called Storage that sits behind a closure (so its private). it has the uid as key.

    element storage then works on a element.store("key", value") and element.retrieve("key")

    and finally, why that matters: events are stored into element storage (eg, Storage[5]['events']) - do element.retrieve("events") and explore that in fireBug if you're curious.

    when you rewrite the innerHTML the old element stops existing. it is then recreated but the event handler AND the reference to the function that you bound earlier will no longer work as it will now get a NEW uid.

    that's about it, hope it makes sense.

    to add a br just do new Element("br").inject(element) instead or create a templated fragment for the lot (fastest) and add in 1 big chunk, adding events after.

提交回复
热议问题