I've been playing around with jQuery's Events methods and I built a simple event bus with the following code:
$(window).on('test:event', function (event, data) {
console.log('Saw a test event: event=%o, data=%o', event, data);
});
$(window).trigger('test:event', {test_data: 'foo'});
My question is, are there any problems with using 'window' to manage the events?
The event acts as an intermediary for exchanging information, isolating and minimizing the dependencies between each side. In this way, message buses create a communication pipeline that is intended to help make your app more maintainable and scalable.
EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.
An event bus is a design pattern (and while we'll be talking about JavaScript here, it's a design pattern in any language) that can be used to simplify communications between different components. It can also be thought of as publish/subscribe or pubsub.
Event-driven architecture pattern is a distributed asynchronous architecture pattern to create highly scalable reactive applications. The pattern suits for every level application stack from small to complex ones. The main idea is delivering and processing events asynchronously.
Yes, this is a great way of using the power of custom jQuery events outside of the context of DOM bubbling. But it can also be done more efficiently (without querying the DOM, since that's performance-expensive and unrelated to the requirements I assume), by using an empty object {}
instead of the window.
Ben Alman wrote a great jQuery plugin for managing events in this way that eschews some of the irrelevant jQuery events elements while using the same principle to achieve a lightweight Publish / Subscribe pattern (listen for and trigger events defined by strings, with optional extra arbitrary data passed between).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With