Reputation: 3389
Why do we need to access the custom event property through 'detail' object?
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
});
}
Upvotes: 5
Views: 705
Reputation: 101
Thats because dispatch is just a wrapper around the DOM CustomEvent Object. Heres the code which returns an dispatch function from the 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);
});
}
};
}
As you can see in the function below it has a signature which takes the second argument named as detail, whatever you pass as a second param it will be detail always. its a javascript thing.
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;
}
Upvotes: 3