Javascript 为什么我们需要通过';细节';苗条的物体?

Javascript 为什么我们需要通过';细节';苗条的物体?,javascript,svelte,svelte-3,svelte-component,Javascript,Svelte,Svelte 3,Svelte Component,为什么我们需要通过“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 wit

为什么我们需要通过“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
        });
    }

这是因为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;
}
导出函数自定义事件(类型:字符串,详细信息?:T){
const e:CustomEvent=document.createEvent('CustomEvent');
e、 initCustomEvent(类型、错误、错误、详细信息);
返回e;
}

这不是苗条特有的。
CustomEvent
模型支持传递数据的
detail
属性。见,我同意。在本机自定义事件中,我们将显式使用“detail”对象。但在这里,我们发送数据时没有将其包装到“detail”对象中。