SoFunction
Updated on 2025-02-28

A brief discussion on jquery event handling

In the front-end development system based on jQuery, many events are often bound by various identifiers on a page. Even if the event proxy is simply used, it still causes the event to be dispersed and difficult to maintain and manage.

So, how to solve this problem? And I thought of events in backbone. as follows:

Copy the codeThe code is as follows:

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

That is, bringing events together is a concept similar to the event processing center.

I briefly sorted out the implementation idea:

Use event proxy method to bind events to body nodes. (Some events themselves do not bubbling, so no research will be done here for the time being)

For the execution object of the event, give a unified identifier.

The execution function of the event is centrally processed.

Copy the codeThe code is as follows:

<body>
    <div data-click-center="handler1"></div>
    <div data-click-center="handler2"></div>  
</body>
// Event handling center
var ClickEventCenter = {
    "handler1": function () {
        // do something...
    },
    "handler2": function () {
        // do something...
    }
    // ...
}
// Event binding
$("click", "[data-click-center]", function () {
    var handlerName = $(this).data("click-center");
    var handler = ClickEventCenter[handlerName]

    if ($.isFunction(handler)) handler()
})

In this way, a type of event is concentrated together.

At some point, it can play a good role.

The above is the entire content of this article, I hope you like it.