Search code examples
javascriptangularjspublish-subscribe

Subscribe an event on child scope and return callback in broadcast\emit


I came after reading @toddmotto excellent post, this, this and this answers, the api And now I have ctrl structur like this

<div ng-controller="ParentCtrl as parent" class="ng-scope">
  <div ng-controller="SiblingOneCtrl as sib1" class="ng-scope"></div>
  <div ng-controller="SiblingTwoCtrl as sib2" class="ng-scope"></div>
  <div class="btn btn-primary"
       ng-click="parent.events.saveDreaft()">
       <span class="glyphicon glyphicon-ok"></span>
       <span>Save</span>
  </div>
</div>

&&

define(['app'], function (app) {    
   app.controller("ParentCtrl", ['$scope', '$q',  function ($scope, $q) {
        var parent= this;  
        parent.data = {};         
        parent.events = {                
            saveDreaft: function() {
                $scope.$broadcast('saveDreaft');
                //return $q(function(resolve, reject) {
                //    try {
                //        var ee = $scope.$broadcast('saveDreaft');
                //        if (ee)
                //            resolve();
                //    } catch (ex) {
                //        reject(ex);
                //    }
                //});
            }
        };
   }]);
});

//=======

define(['app'], function (app) {
  app.controller("SiblingOneCtrl", ['$scope', '$http', '$q', 
   function ($scope, $http, $q) {

        var sib1 = this;            
        sib1.events = {
           saveSib1Form: function () {
                return $http.post('..', ..)
                            .then(function (res) {..})
                            .catch(function (ex) {..});
            }
        };

        var unbind = $scope.$on('saveDreaft', function (event, data) {
            sib1.events.saveSib1Form();
            //return $q.when(sib1.events.saveSib1Form)
            //         .then(function(res) {
            //              event.targetScope.callbackRes = { 
            //                res: res, 
            //                flag: true 
            //              };
            //          })
            //          .catch(..);
         });

        $scope.$on('$destroy', unbind);
    }]);
});

when client click save from the parent scope we want the child run his own save method and then send some callback to the publisher, like jQuery.Callbacks() that he finish maybe $q promise.

Any suggestion ?


Solution

  • You can use $emit to implement a callback-like function in your child scope:

    sib1.events.saveSib1Form();
    $scope.$emit('saveComplete', args);
    

    And register for the $emit event in your parent scope:

    $scope.$on('saveComplete', function(event, args) {
        //your callback code
    })