Javascript pattern: Conditional event handler

前端 未结 5 354
轮回少年
轮回少年 2021-01-27 03:29

Given e.g. a class instance of some sort has a state (e.g. \'active\', \'inactive\', …). The instance also attaches a click event to e.g. a link but the event handler does somet

5条回答
  •  再見小時候
    2021-01-27 04:05

    The answer may be situational, but as always, one should favor simplicity over efficiency, unless there is a performance problem.

    I think that checking conditions in an event handler is a simpler, centralized, and more consistent approach than binding/unbinding event handlers. I often use sitewide click event that checks some user data associated with the HTML element to determine the course of action.

    Similar to your example, one of those actions is "don't do anything", e.g. I've set a flag that indicates it's been disabled. The other option would be to remove the click handler. But this requires more code to do the same thing, and means code control has been split: whereas it used to be entirely in the click handler, now it's in the click handler, and something else that adds or removes the event.

    If the event handler has any perceptible performance impact when bound to the user experience, then maybe you'd want to reconsider this, but I can't think of many situations when it would.

提交回复
热议问题