这个Quiz
block是顶级block。因此,在其编辑功能中,我创建了一个subscribe方法。我能够select 编辑器并获取当前块:
// Subscribe to all changes of the Gutenberg blocks
wp.data.subscribe(() => {
const quiz = wp.data.select("core/editor").getBlock(clientId);
triggerUpdate(quiz);
});
此处简要介绍subscribe方法:
https://www.youtube.com/watch?v=OQczO6VOMkY
这
subscribe()
在编辑页面时,碰巧被调用了数千次,因此我无法找到比手动操作更好的方法;“去盎司”;信息技术:
// Debounce that change, so it wouldn\'t trigger thousands of times
let timeouts = [];
const triggerUpdate = (quiz) => {
while (timeouts.length) {
clearTimeout(timeouts.shift());
}
const timeout = setTimeout(() => {
// ... the code to get the index of each block
}, 1000);
timeouts.push(timeout);
};
现在,每次更新帖子时,我都会触发一个函数,我只需要实际获取索引。通过使用
.innerBlocks
, 一旦在
quiz
(我已经用
wp.data.select("core/editor").getBlock(clientId)
) 然后每次一次
question
.
这样,我就可以循环遍历每个块并使用updateBlockAttributes
// Loop through all nested blocks and update relevant attributes
quiz.innerBlocks.forEach((question, q) => {
let qid = "q" + (q + 1); // qid = "q1", "q2" etc
if (question.attributes.qid != qid) {
const update = {
qid,
questionTitle: "Question " + numToWords(parseInt(q + 1)),
};
console.log(update);
dispatch("core/editor").updateBlockAttributes(
question.clientId,
update
);
}
question.innerBlocks.forEach((answer, a) => {
let aid = qid + "a" + (a + 1); // aid = "q1a2" etc
if (answer.attributes.qid != qid) {
dispatch("core/editor").updateBlockAttributes(answer.clientId, {
aid,
});
}
});
});