Search code examples
javascriptdomcustom-event

Events in a client-side JavaScript application


Writing your own event bus in vanilla JavaScript is straightforward, but are there any advantages to leveraging the built-in DOM event handling API and CustomEvents for an application event bus?


Solution

  • The native DOM events are not as straightforward as one would expect. More details about bubbling and propagation of DOM events. Perhaps that's why each of the modern JS frameworks does not rely on DOM events for handling data.

    Angular 1.x has built in pub/sub system, which is easy to use but it has no relation to what's happening in application logic and can easily become convoluted in large scale app.

    //subscribe and listen
        $scope.$on(name, function(){});
    //emit up or down
        $scope.$broadcast(name, args);
        $scope.$emit(name, args);
    

    ReactJS has another system on its own system to handle events and their data, again with no relation to real DOM. In that case events are more connected to actual state of the application and the variety of ways how that can be done gave rise to set of libraries to handle that - flux, fluxxor, redux, etc.

    There's also tiny (6kb) library with no dependences to handle events flow thought application - PubSubJS.