2

我有一个m("p.help")通过点击事件删除的元素。

如果未单击,我还希望在几秒钟后自动删除该元素。我需要为它设定一个时间。设置超时不起作用。

function help() {
  var text = `This is a service template. Use Service section to set the schedule`;

  var node = m("p.help", {
    onclick() {
      this.parentNode.removeChild(this);
    },
  }, text);

  setTimeout(() => {
    if (node.parentNode) {
      node.parentNode.removeChild(node);
      console.log("removed");
      m.redraw();
    }
  }, 5000);

  return node;
}

点击事件工作正常,但超时不起作用。它甚至没有被触发判断console.log()

我究竟做错了什么?

编辑

感谢 ciscoheat 的提示。

我必须将计时器放入控制器中才能正常工作。

所以这个工作正常:

function controller(init) {
  this.display = {
    help: true
  };
  setTimeout(() => {
    this.display.help = false;
    m.redraw();
  }, 5000);
}

function view(vm) {
  return m(".container", [
    (() => {
      var text = "Some text";
      if (vm.display.help) {
        return m("p.memo", {
          onclick() {
            this.parentNode.removeChild(this);
          }
        }, text);
      }
    })(),
  ]);
}
4

1 回答 1

0

要正确使用 Mithril,您应该避免 DOM 操作,将其留给 Mithril 的快速差异算法。

改用状态变量,与显示 5 秒后自动更改的帮助段落有关。

这是一个显示我的意思的 jsbin:http://jsbin.com/kixece/edit?html,js, output

于 2015-10-29T22:48:07.470 回答