添加事件勾子

WordPress中最强大的概念是有许多的勾子供开发者来修改特定的值,然后我记得前段时间看lit作者在油管上面的一个视频讲到在JavaScript中我们也可以创建一个简单的事件勾子,比如下面这段代码,在我们使用newTaskName 前,我们先发送一个自定义事件,允许项目中的其他代码,或者插件(如果你是写库给别人用)来修改我们这边的待办事项名称。

/**
 * Handles editing a task.
 *
 * @param {CustomEvent} event - The custom event that triggered the function, containing task details.
 *
 * @returns {Promise<void>} - A promise that resolves when the task is updated or an alert is shown on failure.
 */
export default async function editTask(event) {
    // Create a new custom event and pass in task name.
    const event = new CustomEvent("beforeTaskUpdate", {
        bubbles: true,
        detail: {
            task: newTaskName,
        },
    });

    // Dispatch above custom event.
    dialog.dispatchEvent(event);

    // When there are other codes in the project that handle this custom event,
    // the event here will be updated,
    // and this behavior is async, we don't need to await here,
    // event.detail.task will be updated if there is a handler somewhere that modify the value.
    // To testing, we can do something like this:
    // document.addEventListener('beforeTaskUpdate', (event) => {
    //    event.detail.task = event.detail.task + 'test...';
    // });
    // Thoughts: how to handle priority, in the case where multiple codes want to modify this value?
    newTaskName = event.detail.task;
}