我有一个使用 setInterval
来检查某些对象状态的脚本,但它会导致一点延迟,我想知道是否可以使用 MutationObserver
?
我的setInterval
:
var checkExist = setInterval(function() {
var life = 300;
var games = Game.currentGame.ui.playerPetTick.health;
if (games < life) {
console.log("It exists")
clearInterval(checkExist);
}
}, 100); // check every 100ms
我的观察者尝试:
var target = Game.currentGame.ui.playerPetTick.health;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.info("It exists");
});
});
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);
这可以做到吗?
最佳答案
MutationObserver 在这里不会帮助你,因为你的对象似乎不是 DOM 节点。但是您可以使用 getters 轻松实现某种对象观察/setters或proxy objects 。一个简单的例子:
var playerInfo = {
set health(newValue) {
this._health = newValue;
if (this.onhealthchange) {
this.onhealthchange(newValue);
}
},
get health() {
return this._health;
}
};
playerInfo.onhealthchange = function(newValue) {
console.info("Health changed: " + newValue);
};
playerInfo.health = 4;
关于javascript - 使用 MutationObserver 监听变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52575771/