javascript - 监听js变量变化
问题描述
假设有一个代码到位2
var place2IsReady = true;
在地方 1我需要实现以下逻辑:
Once place2IsReady value was changed (to true) then display alert('ready!');
笔记:
- place2IsReady变量在place 1的范围内不可用。
- 位置 1的代码在位置 2执行之前执行(或存在竞争条件)。
解决方案 1
我相信我可以改用 window.place2IsReady 并使用 setTimeout/setInterval 代替 1 直到我得到window.place2IsReady === true
.
有更好的选择吗?使用监听器?关于变量的变化?
PS我只需要跟踪place2IsReady的第一个可能变化。
有没有更好的办法?谢谢你。
解决方案
您可以使用 为变量更改创建一个侦听器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();
}
更通用的侦听器“工厂”可能是:
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);
}
或者也许使用代理(带有设置陷阱)对你有用
const readyState = new Proxy({ ready: false }, {
set (target, prop, val) {
console.log(`readyState.ready changed from ${target[prop]} to ${val}`);
target[prop] = val;
}
});
console.log("Waiting for changes ...");
setTimeout(() => readyState.ready = true, 2000);
推荐阅读
- sql-server - 在 SQL Server 的 Select 语句中选择多列时如何对单列使用不同的关键字
- nginx - 如何在 nginx 中重写 URL?
- postgresql - 项目打开 Dockerfile postgres 未启动
- spring - Spring webflux,测试`ServerResponse`
- vba - 运行宏会导致 Excel 崩溃
- git - 为什么 GitLab api Compare 与 git diff 不同?
- magento - Magento Checkout OnepageController 没有被覆盖
- deck.gl - Deck.GL 自定义层中的工具提示 - Trip Routes
- java - 弹簧 SpEL。如何将null设置为字段的默认值
- java - 如何为行和列创建字符串索引表以及为单元格创建布尔值?