Search code examples
javascriptdom-eventscustom-event

What is the purpose of custom events in javascript?


I am having trouble understanding in what situations you would use custom events. I mean the ones created by the CustomEvent constructor.

I understand the syntax itself, just not why it is useful. It would be nice if somebody could provide an example of real world application of custom events.


Solution

  • I use it (shameless plug) to raise "resize" events on div elements and then use a separate binding framework (aurelia) to listen to those events.

    the explicit code example is:

    var element = this.element; // some element
    var erd = erd({ strategy: 'scroll' });
    
    var widthOld = element.offsetWidth;
    var heightOld = element.offsetHeight;
    
    this.callback = () => {
      var event = new CustomEvent("resize", {
        detail: {
          width: this.element.offsetWidth,
          height: this.element.offsetHeight,
          widthOld: widthOld,
          heightOld: heightOld
        }
      });
      element.dispatchEvent(event);
      widthOld = this.element.offsetWidth;
      heightOld = this.element.offsetHeight;
    };
    
    erd.listenTo(this.element, this.callback);
    

    where erd is element-resize-detector that allows you to detect when any div changes shape.