Discussion on jquery event handling

  • 2020-06-01 08:12:31
  • OfStack

In the front-end development system based on the jQuery library, a large number of events are often bound on a single page by various identifiers. Even the simple use of event proxies still results in scattered events that are difficult to maintain and manage.

So how do you solve this problem? And I think of events in backbone. As follows:


events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  }

In other words, gather the events into one, something like an event processing center.

The following is a simple implementation idea:

Bind events to the body node using an event proxy. (some events do not bubble on their own, so I will not study them here.)

For the execution object of the event, give a uniform 1 identity.

Event execution function, centralized processing.


<body>
    <div data-click-center="handler1"></div>
    <div data-click-center="handler2"></div>  
</body>
// Incident processing center
var ClickEventCenter = {
    "handler1": function () {
        // do something...
    },
    "handler2": function () {
        // do something...
    }
    // ...
}
// event
$body.on("click", "[data-click-center]", function () {
    var handlerName = $(this).data("click-center");
    var handler = ClickEventCenter[handlerName]     if ($.isFunction(handler)) handler()
})

In this case, 1 type of event, concentrated to 1.

In some cases, it can work well.

That's all for this article, I hope you enjoy it.


Related articles: