我有一个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);
}
})(),
]);
}