为什么要事件冒泡,为什么不直接订阅点击事件呢?
我正在阅读一篇关于 ASP.NET 中的事件冒泡的文章,并了解到虽然可以从包含页面订阅用户控件按钮的单击事件,但“这样做会破坏一些面向对象的规则”封装”。更好的想法是在用户控件中发布事件以允许任何感兴趣的各方处理该事件。
我的问题是,从包含页面直接订阅按钮的单击事件将如何破坏面向对象的封装规则?
抱歉,如果这是一个愚蠢的问题。 :|
谢谢!
I was going through an article on event bubbling in asp.net and came to know that although it is possible to subscribe to the click event of a user control's button from the containing page, "doing so would break some of the object oriented rules of encapsulation". A better idea is to publish an event in the user control to allow any interested parties to handle the event.
My question is that exactly how does a direct subscription to the button's click event from a containing page would break the object oriented rules of encapsulation?
Apologies if its a dumb question. :|
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个想法是,控件的按钮是控件 UI 的实现细节。如果您重新发布单击事件,您可以将该按钮重新实现为 ImageButton、LinkButton 等。
我认为,如果按钮是 UI 的永久固定装置,则可以在页面级别将事件处理程序附加到按钮。它节省了大量的事件代码,尤其是大量的按钮。
The idea is that the button of the control is an implementation detail of the UI of the control. If you republish the click event you could reimplement that button as an ImageButton, LinkButton, etc.
I think it's OK to attach an event handler at the page level to the button if the button is a permanent fixture of the UI. It saves a lot of event code, especially with a lot of buttons.
Button 应该由 UserControl 封装。
如果页面直接绑定到按钮上的事件,则页面现在依赖于 UserControl 的内部工作。
页面应该使用 UserControl,而不是 UserControl 的按钮。如果 UserControl 的作者稍后想要删除该按钮并使用一些奇特的新方法来触发其“提交”事件,则您的页面可能会被破坏,因为该按钮可能不再存在。
就此而言,如果 UserControl 的所有者决定在 v1.1 中将按钮从 btnSubmit 重命名为 SubmissionButton,它也可能会破坏您的页面。
最好使用 UserControl 并让它关注自己的内部运作。
The Button is supposed to be encapsulated by the UserControl.
If the Page binds directly to events on the button, then the page is now dependent on the inner workings of the UserControl.
The Page should be consuming the UserControl, not the UserControl's button. If the author of the UserControl later wants to remove the button and use some fancy new method of firing its "Submit" event, your page could be broken because the button may no longer exist.
For that matter, if the owner of the UserControl decides in v1.1 to rename the button from btnSubmit to SubmissionButton, it could break your page, as well.
Better to consume the UserControl and let it be concerned with its own inner workings.