简体   繁体   English

在Typescript中定义对象回调的最佳方法?

[英]best way to define callbacks on objects in Typescript?

I have a sidebar menu component with a service that holds items in the menu. 我有一个带有服务的侧边栏菜单组件,该服务可保存菜单中的项目。 Multiple sources can then alter the menu as they see fit. 然后,多个来源可以根据需要更改菜单。

Currently each item implements SidebarItem: 当前,每个项目都实现SidebarItem:

export interface SidebarItem {
    name: string,
    link: Route|string,
    icon ?: string
}

However I can catch certain events (click, hover) and would like to have an option to define a callback on the sidebar item itself. 但是,我可以捕获某些事件(单击,悬停),并希望有一个选项可以在侧边栏项目本身上定义回调。

I'd like to know the best way to accomplish this. 我想知道实现此目标的最佳方法。 Should I define two properties on the interface and let everyone decide how they implement it, or are there any options? 我应该在接口上定义两个属性,让每个人决定如何实现它,或者有任何选择吗? I don't think sidebar items can be classes, since I don't want a new class for each sidebar item. 我不认为边栏项目可以是类,因为我不希望每个边栏项目都有新的类。

If it helps, I can also dispatch the events using the aurelia event aggregator. 如果有帮助,我还可以使用aurelia事件聚合器调度事件。

PS: If this feels subjective, just read the title as "How to" instead. PS:如果您觉得主观,只需将标题读为“如何”即可。 My proposed method is a wild guess and I don't think it's correct. 我提出的方法是一个疯狂的猜测,我认为这是不正确的。

I ended up going with the following syntax on the interface: 我最终在界面上使用了以下语法:

onClick?: (e: MyEvent) => void

Thanks to Nitzan Tomer in the comments. 感谢Nitzan Tomer的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM