Communicating between a Multiple Controllers and a directive

后端 未结 1 439
深忆病人
深忆病人 2021-01-22 17:08

I have a directive that powers an HTML5 Canvas visualization. This directive has a wide array of methods to modify different parts of the visualization. The issue is that multip

相关标签:
1条回答
  • 2021-01-22 17:36

    I've had the same issue - controllers needing to interact with each other, different parts of the app sending messages to each other, etc. In my projects, I've implemented a MessageService. Here's a very basic version of one (but honestly more than sufficient):

    module.factory('MessageService',
      function() {
        var MessageService = {};
    
        var listeners = {};
        var count = 0;
        MessageService.registerListener = function(listener) {
          listeners[count] = listener;
          count++;
    
          return (function(currentCount) {
            return function() {
              delete listeners[currentCount];
            }
          })(count);
        }
    
        MessageService.broadcastMessage = function(message) {
          var keys = Object.keys(listeners);
    
          for (var i = 0; i < keys.length; i++) {
            listeners[keys[i]](message);
          }
        }
    
        return MessageService;
      }
    );
    

    You might want to have listeners registered for particular subjects, and filter messages by subject, or not. Mine also queue messages on subjects until they're cleared, so that the messages can be viewed when a new view loads (in order to pair for ex. 'Success - Saved file' with a page change).

    0 讨论(0)
提交回复
热议问题