为什么我们需要通过'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
});
}
答案 0 :(得分:2)
那是因为调度只是DOM CustomEvent对象的包装。 这是从瘦仓库中返回调度功能的代码。
/// Construct the initial List of Panels.
List<Panel> _getPanels() {
return [
Panel(
headerValue: 'Panel 1',
expandedValue: _panel1(),
isExpanded: true,
),
Panel(
headerValue: 'Panel 2',
expandedValue: _panel2(),
),
];
}
Function _expansionPanelHeaderBuilderCallback(String title) {
return (BuildContext context, bool isExpanded) {
return ListTile(
title: Text(title),
);
};
}
Widget _buildForm() {
return ExpansionPanelList(
expansionCallback: (int index, bool isExpanded) {
setState(() {
_panels[index].isExpanded = !isExpanded;
});
},
children: [
ExpansionPanel(
headerBuilder: _expansionPanelHeaderBuilderCallback(_panels[0].headerValue),
body: _panel1(),
isExpanded: _panels[0].isExpanded,
canTapOnHeader: true,
),
ExpansionPanel(
headerBuilder:
_expansionPanelHeaderBuilderCallback(_panels[1].headerValue),
body: _panel2(),
isExpanded: _panels[1].isExpanded,
canTapOnHeader: true,
),
],
);
}
Widget _panel1() {
return Padding(...);
}
Widget _panel2() {
return Column(...);
}
正如您在下面的函数中看到的那样,它具有一个签名,该签名采用名为“ detail”的第二个参数,无论您作为第二个参数传递什么,它将始终是detail。这是JavaScript的东西。
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);
});
}
};
}