How to communicate between javascript modules ...?

There are several modules in my application for their own responsibility and that I have some confusion.

  • How to interact between modules?

  • How to inform or listen to modules between decision making for the corresponding scenario.?

Example:

module 1,

var MyModule1 = (function() {
  var myPrivateData = 303;
  function myPrivateFunction() {
    alert('private');
  }
  return {
    myPublicData : 42,
    myPublicFunction : function() {
      alert('public');
    }
  };
})();

Module 2

var MyModule2 = (function() {
  var myPrivateName = privatized;
  function myPrivateFunction() {
    alert(myPrivateName) ;
  }
  return {
    myPublicData : 42,
    myPublicFunction : function() {
      alert('public');
    }
  };
})();

How can I make them communicate and listen to each other.? Can anyone clarify with a small example? I need to share privateData shared with module 2 and the name myPrivate shared with module 1, and in case of any click event that needs to be fired.

Thanks in advance!

+4
source share
2 answers

:

1 - , :

$(document).trigger( "some:event", someData);

2, "some: event", :

$(document).on( "some:event", function(evt,someData) {
   // ... do something with the data ...
} );

. , , , .

+3

-

    var ParentClass = (function() {
     var privateVariable = 'toto';
     this.publicVariable = 'titi';

     this.ChildClass = new ChildClass(this);
     this.ChildClass.execute();
    });

    function ChildClass(parent) { this.parent = parent; return this; };

    ChildClass.prototype.execute = function() {
     alert (this.parent.publicVariable); // show titi
    };

ParentClass();
0

All Articles