4

为什么我们需要通过 'detail' 对象访问自定义事件属性?

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
        });
    }

示例代码在这里

4

1 回答 1

3

那是因为 dispatch 只是 DOM CustomEvent 对象的一个​​包装器。这是从 svelte repo 返回调度函数的代码。

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);
            });
        }
    };
}

正如您在下面的函数中看到的那样,它有一个签名,它接受名为 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;
}
于 2019-12-17T11:35:10.507 回答