/** * Created by robin on 10/24/15. */ (function () { 'use strict'; angular.module('luticate2Utils') .factory('luBusyBusiness', ['$q', function($q) { var luBusyBusiness = {}; luBusyBusiness.groups = null; luBusyBusiness.initGroups = function(groups) { if (typeof groups === 'string') { groups = [groups]; } for (var i = 0; i < groups.length; ++i) { var group = luBusyBusiness.groups[groups[i]]; if (group == null ) { group = { count: 0, deferred: null, errors: [] }; luBusyBusiness.groups[groups[i]] = group; } if (group.count == 0) { group.deferred = $q.defer(); group.errors = []; } ++group.count; } }; luBusyBusiness.isRunning = function(group) { var data = luBusyBusiness.groups[group]; if (data != null) { return data.count > 0; } return false; }; luBusyBusiness.promise = function(group) { var data = luBusyBusiness.groups[group]; if (data != null && data.deferred != null) { return data.deferred.promise; } return null; }; luBusyBusiness.hasError = function(group) { var data = luBusyBusiness.groups[group]; if (data != null) { return data.errors.length != 0; } return null; }; luBusyBusiness.errors = function(group) { var data = luBusyBusiness.groups[group]; if (data != null) { return data.errors; } return null; }; luBusyBusiness.resolve = function(groups) { if (typeof groups === 'string') { groups = [groups]; } for (var i = 0; i < groups.length; ++i) { var group = luBusyBusiness.groups[groups[i]]; if (group != null) { --group.count; if (group.count == 0) { if (!luBusyBusiness.hasError(group)) { group.deferred.resolve(null); } else { group.deferred.resolve(null); } group.deferred = null; } } } }; luBusyBusiness.reject = function(groups, error) { if (typeof groups === 'string') { groups = [groups]; } for (var i = 0; i < groups.length; ++i) { var group = luBusyBusiness.groups[groups[i]]; if (group != null) { --group.count; group.errors.push(error); if (group.count == 0) { group.deferred.resolve(null); group.deferred = null; } } } }; luBusyBusiness.reset = function() { luBusyBusiness.groups = {}; return luBusyBusiness; }; return luBusyBusiness; }]); })();