D
D
Dima nahkar2015-01-14 01:11:40
JavaScript
Dima nahkar, 2015-01-14 01:11:40

How does communication between Javascript modules work?

Hello everyone, I decided to figure out how to organize communication between modules, and came across an article on Habré, but I just can’t understand how it is called and works, what is transmitted. Please tell me
// Loosely coupled
var Module1 = {
"init": function ($) {
$.on('event', function (e) { // $ is not jQuery, it's a sandbox instance
console.log(e.data) ;
});
}
};

var Module2 = {
"someAction": function ($) { // $ is not jQuery
$.trigger('event', 'data');
}
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2015-01-14
Protko @Fesor

When the someAction method is called on a module, the module fires an event (a global event for all components that subscribe to it). In your example, Module1 in the init method subscribes to the event and does something about it.
Read about the observer pattern and all that. It is important to understand where to apply this approach and where it is better to explicitly call the method of another module.

P
Pavel Elizariev, 2015-01-14
@effetto

For the purpose of breaking down the client application into modules, I use the AMD approach . The most popular implementation of this mechanism is provided in RequireJS . AMD's approach as a whole is now very popular, because with little effort it allows you to implement asynchronous module loading.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question