Pub/Sub design pattern angularjs service

后端 未结 2 825
小鲜肉
小鲜肉 2021-01-27 05:41

I\'ve been trying to use the answer here posted by Mark Rajcok

angular JS - communicate between non-dependend services

I am having trouble understanding his answ

相关标签:
2条回答
  • 2021-01-27 06:34

    Is the event1ServiceHandlers array populated with functions (here called handler) that is triggered in this forEach loop?

    Yes

    how does service 1 execute a function on service 2 if service 2 already has service 1 as a dependency

    Create service 3, NotificationService as before:

    .factory('NotificationService', [function() {
        var event1ServiceHandlers = [];
        return {
            // publish
            event1Happened: function(some_data) {
                angular.forEach(event1ServiceHandlers, function(handler) {
                    handler(some_data);
                });
            },
            // subscribe
            onEvent1: function(handler) {
                event1ServiceHandlers.push(handler);
            }
        };
    }])
    

    Have service 2 register a callback function with the NotificationService:

    .factory('Service2', ['NotificationService',
    function(NotificationService) {
        // event1 handler
        var doSomething = function(someData) {
            console.log('S2', someData);
            // do something here
        }
        // subscribe to event1
        NotificationService.onEvent1(doSomething);
        return {
          // define public API for Service2 here
        }
    }])
    

    Whenever service 1 wants function doSomething() on service 2 to execute, it can publish the event1Happened event:

    .factory('Service1', ['NotificationService',
    function(NotificationService) {
        var someData = ...;
        return {
           // define public API for Service1 here
           callService2Method: function() {
             // publish event
             NotificationService.event1Happened(someData);
           }
        }
    }])
    
    0 讨论(0)
  • 2021-01-27 06:37

    In his example, NotificationService is a new service that any of the existing services would depend on. He provided an implementation of Service1 but Service2 would essentially be the same...both depend on NotificationService and neither know about each other.

    Service1 and Service2 each subscribe to events by calling NotificationService.onEvent1(event1Happened); and trigger events by calling NotificationService.event1Happened(my_data);.

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