Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why event bubbling and why not directly subscribe the click event?

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!

like image 220
Dienekes Avatar asked Jul 02 '10 18:07

Dienekes


2 Answers

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.

like image 177
Toby Avatar answered Nov 10 '22 18:11

Toby


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.

like image 22
BC. Avatar answered Nov 10 '22 19:11

BC.