假设在位置 2
中有一个代码var place2IsReady = true;
在位置 1 我需要实现以下逻辑:
Once place2IsReady value was changed (to true) then display alert('ready!');
注意事项:
解决方案 1
我相信我可以改用 window.place2IsReady 并在第 1 处使用 setTimeout/setInterval 直到我得到 window.place2IsReady === true
。
还有更好的选择吗?使用监听器?关于变量的变化?
附言我只需要跟踪place2IsReady的第一个可能的变化。
有没有更好的办法?谢谢。
答案 0 :(得分:1)
您可以使用 capture(pageableCaptor)
为变量更改创建侦听器,例如:
setTimeout
更通用的侦听器“工厂”可能是:
let place2IsReady = false;
setReadyListener();
// testing wait 2 seconds to set place2IsReady to true
// so: an alert should occur after 2 seconds
setTimeout(() => place2IsReady = true, 2000);
function setReadyListener() {
const readyListener = () => {
if (place2IsReady) {
return alert("Ready!");
}
return setTimeout(readyListener, 250);
};
readyListener();
}
或者也许使用Proxy(带有设置陷阱)适合您
let place2IsReady = false;
let fromObj = {
place2IsReady: "busy",
done() { this.place2IsReady = "done"; },
};
const listen = changeListenerFactory();
listen(
() => place2IsReady,
() => console.log("place2IsReady") );
listen(
() => fromObj.place2IsReady === "done",
() => console.log("formObj.place2IsReady done!") );
console.log("Listening...");
// test change variables with listeners
setTimeout(() => place2IsReady = true, 1000);
setTimeout(() => fromObj.done(), 3000);
function changeListenerFactory() {
const readyListener = (condition, callback, delay) => {
if (!condition || typeof condition !== "function") { return true; }
if (condition()) {
return callback();
}
setTimeout(() => readyListener(condition, callback, delay), delay);
};
return (condition, callback = () => {}, delay = 250) =>
readyListener(condition, callback, delay);
}
答案 1 :(得分:0)
假设你可以用一个对象替换 place2IsReady:
place2IsReady = {
state: false,
set ready(value) {
this.state = value
state && place_1_call()
},
get ready() {
return state
}
}
place_1_call = () => {
alert('ready')
}
place2IsReady.ready = true