Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use 'window' as an event bus in jQuery?

Tags:

jquery

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?

like image 766
Darrell Brogdon Avatar asked Feb 21 '13 17:02

Darrell Brogdon


People also ask

What is the purpose of event bus?

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.

What is EventBus?

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.

What is EventBus JavaScript?

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.

What is event bus architecture?

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.


1 Answers

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).

like image 116
Barney Avatar answered Sep 21 '22 00:09

Barney