How to use $ broadcast (), $ emit () and $ on () in AngularJS

6

I understand that $emit() and $broadcast are emitters, and $on is an event listener. I'm working with unit tests and I'm not getting access to the following function:

eventHandler.service.js

(function () {
'use strict';

angular.module("app")

    .service('EventHandler', EventHandler);

EventHandler.$inject = ['$rootScope', '$location', '$animate', '$state', '$stateParams', '$sanitize', '$q', '$uibModal', 'toastr',
    'storage', 'StorageService', 'LogService', 'LanguageResource', 'LoginService', 'StcpUtilsService', 'DAOService',
    'CSRF', 'Authorization', 'ShortcutService', 'data_login', 'PermissionsService', 'BusinessLogicService', 'DebugMode'
]; 

function EventHandler($rootScope, $location, $animate, $state, $stateParams, $sanitize, $q, $uibModal, toastr, storage, StorageService,
                      LogService, LanguageResource, LoginService, StcpUtilsService, DAOService, CSRF,
                      Authorization, ShortcutService, data_login, PermissionsService, BusinessLogicService, Debug) {

    var animate;
    /* = parameters.$animate || $animate; */
    var rootScope;
    /* = parameters.$rootScope || $rootScope; */
    var scope;
    /* = parameters.$scope; */
    var _toastr;
    /* = parameters.toastr || toastr; */
    var _storage;
    /* = parameters.StorageService || StorageService; */
    var location;
    /* = parameters.$location || $location; */
    var log;
    /* = parameters.LogService ? parameters.LogService.log : LogService.log || LogService.log; */
    var language;
    /* = parameters.LanguageResource || LanguageResource; */
    var shortcut;
    var t;
    var dao;
    var DebugMode;

    return {
        initialize: initialize_component,
        onCheckSession: onCheckSessionHandle,
        onLogin: onLoginHandle,
        onLogout: onLogoutHandle,
        onStateChangeError: onStateChangeErrorHandle,
        onHideMenuCheck: onHideMenuCheckHandle,
        onSetInstance: onSetInstanceHandle,
        onRemoveInstance: onRemoveInstanceHandle,
        onGetInstanceName: onGetInstanceNameHandle,
        onGetInstanceId: onGetInstanceIdHandle,
        onGetOperatorLogged: onGetOperatorLoggedHandle,
        onOperatorIsLogged: onOperatorIsLoggedHandle,
        onShakeMenu: onShakeMenuHandle,
        onCheckInstance: onCheckInstanceHandle,
        onSave: onSaveHandle,
        onDelete: onDeleteHandle,
        onInterceptError: onInterceptErrorHandle,
        onChangeOperatorPassword: onChangePasswordHandle,
        onGetTransfer: onGetTransferHandle,
        onOpenChangeModuleDialog: onOpenChangeModuleDialogHandle,
        onChangeSubModule: onChangeSubModuleHandle,
        onDisplaySelectionInstance: onDisplaySelectionInstanceHandle,
        onGetInstances: onGetInstancesHandle,
        onCheckModule: onCheckModuleHandle,
        // onDataToPersist: onDataToPersistHandle
    };

    // function onDataToPersistHandle() { rootScope.$on('dataToPersist', onDataToPersist); }
    function onRemoveInstanceHandle() {
        rootScope.$on('removeInstance', onRemoveInstance);
    }        

    function onRemoveInstance(ev, args) {
        onCheckSession(ev, args);

        if (ev.defaultPrevented === false) {
            _storage[storage].del("instance_id");
            _storage[storage].del("instance_name");
            _storage.local.del("instance_name");
            _storage.local.del("instanceSelected");
            _storage.session.del("instanceSelected");
            rootScope.instanceSelected = undefined;
            delete rootScope.displaySelectionInstance;
            delete rootScope.instance_id;
            delete rootScope.instance_name;
        }
    } //...

I'm doing the tests in the following way, but I can not test the "onRemoveInstance" function, they told me to apply some emitter so I can get access to it. You need to know how to make ev.defaultPrevented be false.

testEventHandlerService.Spec.js

describe('Testing EventHandler', function () {
beforeEach(module('app'));

var srv, rootScope, injector, httpBackend, animate, scope, location, loginService, _toastr, _storage, dao, log, language;

beforeEach(inject(function (EventHandler,_$injector_, $rootScope, $httpBackend, $animate, $location, LoginService, toastr, storage, StorageService, LogService, DAOService, LanguageResource) {
  injector = _$injector_;
  srv = EventHandler;
  rootScope = $rootScope;          
  animate = $animate;
  location = $location;
  loginService = LoginService;
  _toastr = toastr;
  _storage = StorageService;
  log = LogService;
  language = LanguageResource;
  dao = DAOService;


  srv.initialize({
      $rootScope: rootScope,
      $animate: animate,
      $scope: $rootScope.$new(),
      $location: location,
      _toastr: toastr,
      _storage: StorageService,
      log: LogService,
      language: LanguageResource,
      dao: DAOService,
  })

//   rootScope.$on('doLogin', null);      
}));    

it('testing if the onRemoveInstance function', function(){  
    srv.ev = {defaultPrevented: false}; //testando para ver se da certo      
    srv.onRemoveInstance();       
    rootScope.$emit('removeInstance', srv.onRemoveInstance); 
});

it('testing if the onChangeSubModule function', function(){        
    srv.onChangeSubModule();       
    rootScope.$emit('changeSubModule', srv.onChangeSubModule);   
});

If possible can someone give me a real-time example of using the three?

    
asked by anonymous 04.10.2017 / 15:41

1 answer

5

$emit and $broadcast are very similar. As you said, both are to shoot something. I will try to explain very simply

The $broadcast calls the event of everyone who is "below" it, would be the same children. $emit calls all events with that name. He's a guy who shoots globally.

The $on is the listener, so it will be activated when called by a $emit or $broadcast

I do not know what you want to do there in your code, but it would be something like this:

$scope.$on('onRemoveInstance', function(ev, args) {
onCheckSession(ev, args);

        if (ev.defaultPrevented === false) {
            _storage[storage].del("instance_id");
            _storage[storage].del("instance_name");
            _storage.local.del("instance_name");
            _storage.local.del("instanceSelected");
            _storage.session.del("instanceSelected");
            rootScope.instanceSelected = undefined;
            delete rootScope.displaySelectionInstance;
            delete rootScope.instance_id;
            delete rootScope.instance_name;
        }
});

// Aqui embaixo eu chamo minha função. Essa minha chamada pode ser feita em qualquer lugar do código, inclusive em outro arquivo javascript em um outro controller.

$scope.$emit('onRemoveInstance', $scope.ALGUMACOISA);

As a request, I'm also leaving here this Plunker showing this in practice.

Enjoy and also read about $ ROOTSCOPE in the official AngularJS documentation

    
04.10.2017 / 16:33