You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Observer Pattern as a service for angularJS
Examples to follow
About
This is an angular factory which reflects the Observer Pattern it works well with the ControllerAs method of working as it can be much more efficient that $scope.$watch and more specific to a unique scope or object than $emit and $broadcast when used correctly.
Use Case: You would use this pattern to communicate between 2 controllers that use the same model but are not connected in anyway
notifies all observers of a specific event, can pass a params variable of any type
Controller Example
Below example shows how to attach, notify and detach an event.
angular.module('app.controllers')
.controller('ObserverExample',ObserverExample);
ObserverExample.$inject= ['ObserverService','$timeout'];
function ObserverExample(ObserverService, $timeout) {
var vm = this;
var id = 'vm1';
ObserverService.attach(callbackFunction, 'let_me_know', id)
function callbackFunction(params){
console.log('now i know');
ObserverService.detachByEvent('let_me_know')
}
$timeout(function(){
ObserverService.notify('let_me_know');
},5000);
}
Alternative way to remove event
angular.module('app.controllers')
.controller('ObserverExample',ObserverExample);
ObserverExample.$inject= ['ObserverService','$timeout', '$scope'];
function ObserverExample(ObserverService, $timeout, $scope) {
var vm = this;
var id = 'vm1';
ObserverService.attach(callbackFunction, 'let_me_know', id)
function callbackFunction(params){
console.log('now i know');
}
$timeout(function(){
ObserverService.notify('let_me_know');
},5000);
// Cleanup listeners when this controller is destroyed
$scope.$on('$destroy', function handler() {
ObserverService.detachByEvent('let_me_know')
});
}