为什么我们需要通过 Svelte 中的“detail”对象访问自定义事件数据?

Raj*_*dda 5 javascript svelte svelte-component svelte-3

为什么我们需要通过“详细信息”对象访问自定义事件属性?

function handleMessage(event) {

    alert(event.detail.text); // why do we need to access 'text' property from 'detail' object?

}



// In the Child component, we are using this function to dispatch the custom event with some data.

    function sayHello() {
        dispatch('message', {
            text: 'Hello!'  // we are not wrapping the data into the 'detail' object
        });
    }
Run Code Online (Sandbox Code Playgroud)

示例代码在这里

小智 3

那是因为调度只是 DOM CustomEvent 对象的包装器。这是从 svelte 存储库返回调度函数的代码。

export function createEventDispatcher() {
    const component = get_current_component();

    return (type: string, detail?: any) => {
        const callbacks = component.$$.callbacks[type];

        if (callbacks) {
            // TODO are there situations where events could be dispatched
            // in a server (non-DOM) environment?
            const event = custom_event(type, detail);
            callbacks.slice().forEach(fn => {
                fn.call(component, event);
            });
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

正如您在下面的函数中看到的,它有一个签名,该签名采用名为“detail”的第二个参数,无论您作为第二个参数传递什么,它都将始终是“detail”。这是一个 javascript 的事情。

export function custom_event<T=any>(type: string, detail?: T) {
    const e: CustomEvent<T> = document.createEvent('CustomEvent');
    e.initCustomEvent(type, false, false, detail);
    return e;
}
Run Code Online (Sandbox Code Playgroud)