Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Combining Raynos's concerns about encapsulation with the OP's clarification that he wants to expose a couple of methods on a messaging service, this is I think the right way to go about it:</p> <pre><code>// In messagingServiceSingleton.js define(function () { var messagingService = new MessagingService(); return { notify: messagingService.listen.bind(messagingService), listen: messagingService.notify.bind(messagingService) }; }); // In bar.js define(["./messagingServiceSingleton"], function (messagingServiceSingleton) { messagingServiceSingleton.listen(/* whatever */); } // In baz.js define(["./messagingServiceSingleton"], function (messagingServiceSingleton) { messagingServiceSingleton.notify(/* whatever */); } </code></pre> <p><code>Function.prototype.bind</code> will not be present in all browsers, so you would need to include a polyfill like <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind" rel="noreferrer">the one Mozilla provides</a>.</p> <p>An alternate (and in my opinion probably better) approach would be to make the messaging service object itself a module. This would look something like</p> <pre><code>// In messagingService.js define(function () { var listenerMap = {}; function listen(/* params */) { // Modify listenerMap as appropriate according to params. } function notify(/* params */) { // Use listenerMap as appropriate according to params. } return { notify: notify listen: listen }; }); </code></pre> <p>Since you expose the same <code>notify</code> and <code>listen</code> methods to everyone who uses your module, and those always refer to the same <a href="http://javascript.crockford.com/private.html" rel="noreferrer">private</a> <code>listenerMap</code> variable, this should do what you want. It also obviates the need for <code>Function.prototype.bind</code>, and gets rid of the rather-unnecessary distinction between the messaging service itself and the module which enforces singleton usage of it.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload