为什么我们需要在 Svelte 中通过 'detail' 对象访问自定义事件数据?
Why do we need to access the custom Event data through 'detail' Object in Svelte?
为什么我们需要通过'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 对象的包装器。
这是 returns 来自 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;
}
为什么我们需要通过'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 对象的包装器。 这是 returns 来自 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;
}