DEV Community

code plato
code plato

Posted on

How to write elegant code 1: Keep the chain of event calls short

The chain of event calls

There are some scenarios we keep throw up the event to the parent component. Then it handle the event in the component far way from the component which raise the event

Image description

This has the following disadvantages

  • Switching between different component source code increase the difficulty of developing
  • We coupling deeply these components. The architecture is fragile. If there is a component updated might break the event chain

If we calculate the distance of event calls chain in this way:

  • when the event is handled in the same component which fire it, the distance is 0
  • if the event if handled in the parent component we plus 1 to the distance. For example, the event is handled by the parent component, the distance is 1

In the example above, the distance is 3

Image description

The code is hard to read if the distance is larger than 1. If it’s 3, you will need to switch 4 files to read the event call chain completely.

How to fix it

Put the even handler beside the event listener

Questions

  • Q: Will this cause a lot of duplicate code? A: No. we can extract common code to composable or component to reuse the same code.
  • Q: Will this create a lot of duplicate components like modals? A: No, make sure the component only be created when it's needed. For example if you are using Vue.js use v-if instead of v-show for modal component to make sure it won’t be rendered when no needed. Also, use private variable instead of global variable to control if the modal is shown to make sure the toggle method will only trigger 1 modal to be open or close.

Top comments (0)