Search code examples
jqueryember.jsember-cliember-components

Ember element/component removal behaves unexpectedly [twiddle provided]


Basically Im trying to add visualilzation to a delete action.

And the code im using:

    {{#each wrappedRecords as |record|}}
        {{#fade-element}}
                {{record.name}}
                <span class="remove" {{action "removeRecord" record}}></span>
            </span>
        {{/fade-element}}
    {{/each}}

So the removeRecord action is being triggered and a record is removed from wrappedRecords

And now in my fade-element component wrapper. I catch component destroy in willDestroyElement hook.

export default Ember.Component.extend({
       willDestroyElement : function () {
            var clone = this.$().clone();
            clone.insertAfter(this.$());
            clone.fadeOut();
        },
});

And it does not work however when i replace:

clone.insertAfter(this.$()); with clone.insertAfter(this.$().parent());

It does work but then a new problem comes up. E.g:

I have 2 items and i try to remove the first it would look like this

X1 (to delete) X2 (second element) X1 (Clone that was appeneded to parent)

Link to live demo

https://ember-twiddle.com/ef8c4bcdcd8d2eb5b5c4?openFiles=fade-element.component.js%2Cfade-element.template.hbs


Solution

  • So two things:

    1. The parent contains the X2, so naturally inserting an element after the parent will not work.
    2. The view is about to be torn down, so you can't use it, and the parent view will rerender, so you can't put the element inside it and expect it to stick.

    The solution is

    1. Wait until after the rerender takes place using Ember.run.schedule('afterRender', ...). To learn more about the Ember Run Loop, see https://guides.emberjs.com/v2.4.0/applications/run-loop/
    2. Save a reference to the previous element so that you know where you can place the clone.

    See https://ember-twiddle.com/966c8c6d364e0f631c0b?openFiles=fade-element.component.js%2Cfade-element.template.hbs for the solution as a twiddle.