Moving from classic event management to event delegation in JavaScript OOP

前端 未结 1 559
走了就别回头了
走了就别回头了 2021-01-16 15:00

The old event management in which each handler for specific actions was directly attached to the target element is becoming outdated, since considerations about performance

1条回答
  •  被撕碎了的回忆
    2021-01-16 15:54

    it clashes with the event delegation paradigm.

    Forget that paradigm! Don't choose it because it's "cool" and directly attaching events "is becoming outdated", choose it only when it is necessary. Event delegation is not necessary for you, nor does it speed up anything. It is not a solution you can apply - you have no problem!

    You have one element and a single element-specific event handler function (every widget expander has its own function). You can already infer from your problems applying event delegation that you cannot and should not use it here. Attach the handlers directly.

    Event delegation is only useful when you have a vast amount of similar elements, located consistently in the DOM with one common ancestor, that would all going to be attached the same event handler function. This is not the case with your Widget constructor that does take instance-specific options such as the expander selector.

    In your current Widget class, using event delegation would clash with the single responsibility principle. In the event delegation paradigm, you would need to see the elements in the delegation context as a whole, being as homogeneous as possible. The more element-specific data and state you add, the more delegation advantages you are loosing.

    If you really want to use event delegation here, I would suggest something like

    var Widgets = {
        init: function(delegationContext) {
            $(delegationContext).on("click", ".widget-expander", function(e) {
                 $this = $(this);
                 $this.next().toggle($this.data("widget-expander-timeout") || 500);
            });
        },
        activate: function(options) {
            $(options.expander)
             .addClass("widget-expander")
             .data("widget-expander-timeout", options.timeout);
        }
    };
    

    Here no constructors are used. You just initialise the event delegation context, and then you can add single elements to be captured by the delegation mechanism. All data is stored on the element, to be accessible from the event handler. Example:

    Widgets.init('.widgetContainer');
    Widgets.activate({expander: '.expanders', timeout: 800});
    

    And what are the main trends of other developers you heard about as far as today?

    Apart from that question being off-topic on StackOverflow, I can only advise you not to follow every trend someone heard about. Learn about new (or advertised or fancy) technologies, yes, but do not forget to learn about when to use them.

    0 讨论(0)
提交回复
热议问题