ashark
ashark

Reputation: 28

In mithril.js, onremove and onbeforeremove events not firing, while oninit and oncreate are

File TodoApp.js:

...
const Todo = {
  oninit(vnode) {
    ...
    // ok
  },
  oncreate() {
    ...
    // ok
  },
  onbeforeremove() {
    ...
    // not firing
  },
  onremove() {
    ...
    // not firing
  }
};
...

I was trying to do some cleanup in onremove or onbeforeremove, but both are not working.
Is there something like componentWillUnmount of React in mithril.js?

Upvotes: 0

Views: 554

Answers (1)

Ian Wilson
Ian Wilson

Reputation: 9079

They should be similar, except onbeforeremove only applies to the topmost element being detached, as I understand it. I think maybe something else is causing those to not fire. Are you sure the TODO is not being hidden with css or another error is being silenced before the hooks can be executed?

Maybe you need to post more of your code to debug.

I made a simple example, using MithrilJS 2.0.4, that demonstrates the difference between onbeforeremove and onremove.

after toggle on:

TODO.oncreate <div>​…​</div>​
TODOContent.oncreate <div>​Get something done​</div>​

after toggle off:

TODO.onbeforeremove <div>​…​</div>​
TODO.onremove <div>​…​</div>​
TODOContent.onremove <div>​Get something done​</div>​

The first click of the button shows the TODO and TODOContent and the second click of the button destroys the TODO and TODOContent. onbeforeremove is only called for TODO but onremove is called for both TODO and TODOContent.

const TODOContent = {
  oncreate: function (vnode) {
    console.log('TODOContent.oncreate', vnode.dom);
  },
  onbeforeremove: function (vnode) {
    console.log('TODOContent.onbeforeremove', vnode.dom);
  },
  onremove: function (vnode) {
    console.log('TODOContent.onremove', vnode.dom);
  },
  view: function () {
    return m('div', 'Get something done');
  }  
}

const TODO = {
  oncreate: function (vnode) {
    console.log('TODO.oncreate', vnode.dom);
  },
  onbeforeremove: function (vnode) {
    console.log('TODO.onbeforeremove', vnode.dom);
  },
  onremove: function (vnode) {
    console.log('TODO.onremove', vnode.dom);
  },
  view: function () {
    return m('div', m(TODOContent));
  }
};

function TODOWrapper(vnode) {
  let show = false;
  function toggle(e) {
    show = !show;
  }
  return {
    view: function (vnode) {
      return m('div', [
        m('button[type=button]', {onclick: toggle}, 'toggler'),
        show ? m(TODO) : null,
        ]);
    }
  }
}
  

m.mount(document.body, {view: function () { return m(TODOWrapper);}});

Upvotes: 2

Related Questions