Establishing Clear Guidelines for Event Delegation
Create protocols for implementing event delegation to enhance code efficiency and user experience in your applications.
0 likes
162 views
Rule Content
{
"title": "Establishing Clear Guidelines for Event Delegation",
"description": "Create protocols for implementing event delegation to enhance code efficiency and user experience in your applications.",
"category": "JavaScript Cursor Rules",
"rules": [
{
"id": "event-delegation-parent-selection",
"description": "Attach event listeners to the closest stable parent element that encompasses all target child elements to ensure efficient event handling.",
"severity": "warning",
"pattern": "document\\.querySelector\\(.*\\)\\.addEventListener\\(.*\\)",
"fix": "Identify a common ancestor element and attach the event listener to it instead of individual child elements."
},
{
"id": "event-delegation-target-validation",
"description": "Validate the event target using specific selectors to ensure the event originated from the intended child element.",
"severity": "warning",
"pattern": "event\\.target\\.matches\\(.*\\)",
"fix": "Use 'event.target.matches()' or 'event.target.closest()' to accurately identify the target element."
},
{
"id": "event-delegation-throttling",
"description": "Implement throttling or debouncing for events that fire frequently, such as 'scroll' or 'resize', to enhance performance.",
"severity": "warning",
"pattern": "addEventListener\\(\\s*['\"](scroll|resize)['\"]\\s*,\\s*function\\s*\\(.*\\)\\s*{",
"fix": "Wrap the event handler in a throttling or debouncing function to limit the rate at which the handler is executed."
},
{
"id": "event-delegation-avoid-over-delegation",
"description": "Avoid delegating too many events to a single parent element, as it can lead to inefficient event handling and maintenance challenges.",
"severity": "warning",
"pattern": "document\\.addEventListener\\(.*\\)",
"fix": "Delegate events to the nearest common ancestor of the target elements rather than the document to improve performance and maintainability."
},
{
"id": "event-delegation-dynamic-content",
"description": "Ensure event delegation accounts for dynamically added elements to maintain consistent event handling.",
"severity": "warning",
"pattern": "parentElement\\.addEventListener\\(.*\\)",
"fix": "Use event delegation on a stable parent element to handle events for both existing and dynamically added child elements."
}
]
}