gpt4 book ai didi

javascript - 如何将 MutationObserver 与对象一起使用?

转载 作者:行者123 更新时间:2023-12-02 21:58:20 25 4
gpt4 key购买 nike

我有以下对象:

mind = {
queries: [],
actions: []
};

我根据另一个函数更新查询操作

我想检测它们每次更新和更改的时间,并且我听说过 MutationObserver,所以我尝试调用它:

var muob = (window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver);
var ob = new muob(function(m) {
console.log('It works!');
});
ob.observe(mind, { subtree: true });

但是这不起作用。我得到的返回:

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

我的代码有什么问题吗?

最佳答案

MutationObserver 仅适用于 DOM 元素,不适用于对象:

var ob = new MutationObserver(function(m) {
console.log('It works!');
});
ob.observe(mind, { childList: true });

mind.textContent = 'foo';
<div id="mind"></div>

对于您正在做的事情,您可以使 queriesactions 属性具有更新数组的方法,例如:

const mind = {
_queries: [],
_actions: [],
queries: {
push(...args) {
console.log('Push detected');
mind._queries.push(...args);
},
get() {
return mind._queries;
}
},
actions: {
push(...args) {
console.log('Push detected');
mind._actions.push(...args);
},
get() {
return mind._actions;
}
}
};

mind.queries.push('foo');
console.log(mind.queries.get());

或者,使用代理:

const handler = {
set(obj, prop, newVal) {
console.log('Change detected');
return obj[prop] = newVal;
},
get(obj, prop) {
return obj[prop];
}
};

const mind = {
queries: new Proxy([], handler),
actions: new Proxy([], handler),
};

mind.queries.push('foo');
console.log(mind.queries);

(上面的代码片段记录 ChangeDetected 两次,因为它必须更新数组上的 0 属性更改数组的 .长度)

不过,这还是很奇怪 - 如果在代码中更改数组的位置,您还调用另一个函数(It Works! 部分)来表示已发生更新。

关于javascript - 如何将 MutationObserver 与对象一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59945965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com