CRM-15578 - Add crmMailingAB2 module (based on crmMailingAB). Add skeletal list/edit...
[civicrm-core.git] / js / angular-crm-util.js
1 /// crmUi: Sundry UI helpers
2 (function (angular, $, _) {
3 angular.module('crmUtil', []);
4
5 // Adapter for CRM.status which supports Angular promises (instead of jQuery promises)
6 // example: crmStatus('Saving', crmApi(...)).then(function(result){...})
7 angular.module('crmUtil').factory('crmStatus', function($q){
8 return function(options, aPromise){
9 return CRM.toAPromise($q, CRM.status(options, CRM.toJqPromise(aPromise)));
10 };
11 });
12
13 // crmWatcher allows one to setup event listeners and temporarily suspend
14 // them en masse.
15 //
16 // example:
17 // angular.controller(... function($scope, crmWatcher){
18 // var watcher = crmWatcher();
19 // function myfunc() {
20 // watcher.suspend('foo', function(){
21 // ...do stuff...
22 // });
23 // }
24 // watcher.setup('foo', function(){
25 // return [
26 // $scope.$watch('foo', myfunc),
27 // $scope.$watch('bar', myfunc),
28 // $scope.$watch('whiz', otherfunc)
29 // ];
30 // });
31 // });
32 angular.module('crmUtil').factory('crmWatcher', function(){
33 return function() {
34 var unwatches = {}, watchFactories = {}, suspends = {};
35
36 // Specify the list of watches
37 this.setup = function(name, newWatchFactory) {
38 watchFactories[name] = newWatchFactory;
39 unwatches[name] = watchFactories[name]();
40 suspends[name] = 0;
41 return this;
42 };
43
44 // Temporarily disable watches and run some logic
45 this.suspend = function(name, f) {
46 suspends[name]++;
47 this.teardown(name);
48 var r;
49 try {
50 r = f.apply(this, []);
51 } finally {
52 if (suspends[name] === 1) {
53 unwatches[name] = watchFactories[name]();
54 if (!angular.isArray(unwatches[name])) {
55 unwatches[name] = [unwatches[name]];
56 }
57 }
58 suspends[name]--;
59 }
60 return r;
61 };
62
63 this.teardown = function(name) {
64 if (!unwatches[name]) return;
65 _.each(unwatches[name], function(unwatch){
66 unwatch();
67 });
68 delete unwatches[name];
69 };
70
71 return this;
72 }
73 });
74
75 // example: scope.$watch('foo', crmLog.wrap(function(newValue, oldValue){ ... }));
76 angular.module('crmUtil').factory('crmLog', function(){
77 var level = 0;
78 var write = console.log;
79 function indent() {
80 var s = '>';
81 for (var i = 0; i < level; i++) s = s + ' ';
82 return s;
83 }
84 var crmLog = {
85 log: function(msg, vars) {
86 write(indent() + msg, vars);
87 },
88 wrap: function(label, f) {
89 return function(){
90 level++;
91 crmLog.log(label + ": start", arguments);
92 var r;
93 try {
94 r = f.apply(this, arguments);
95 } finally {
96 crmLog.log(label + ": end");
97 level--;
98 }
99 return r;
100 }
101 }
102 };
103 return crmLog;
104 });
105
106 })(angular, CRM.$, CRM._);