提问人:Anjan Talatam 提问时间:4/8/2023 更新时间:4/8/2023 访问量:950
突变观察者回调函数中Mutation列表的打字稿类型是什么
What is the typescript type of Mutation list in callback function of mutation observer
问:
回调函数中的打字稿类型是什么?mutationList
const targetNode = document.getElementById("some-id");
const config = { attributes: true, childList: true, subtree: true };
const callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
答:
0赞
Anjan Talatam
4/8/2023
#1
突变记录[]
const callback = (mutationList: MutationRecord[], observer: MutationObserver) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
或
const callback: MutationCallback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
建议:为回调函数分配类型,而不是将其分配给每个参数。
interface MutationCallback {
(mutations: MutationRecord[], observer: MutationObserver): void;
}
评论
new MutationObserver
MutationCallback
cmd+click
MutationObserver
MutationCallback