UNPKG

1.62 kBJavaScriptView Raw
1var isFunction = require('x-common-utils/isFunction');
2
3/**
4 * Cancel controller is used to cancel actions. One controller can bind any number of actions.
5 *
6 * @class
7 */
8function CancelController() {
9 /**
10 * @type {boolean} Whether the controller is canceled.
11 */
12 this.canceled = false;
13
14 /**
15 * @type {Function[]} The callbacks to call on cancel.
16 */
17 this.callbacks = [];
18}
19
20/**
21 * Cancel the actions that bind with this cancel controller.
22 */
23CancelController.prototype.cancel = function () {
24 var callbacks = this.callbacks;
25 var i = 0;
26 var l = callbacks.length;
27
28 if (this.canceled === false) {
29 this.canceled = true;
30
31 for ( ; i < l; i += 1) {
32 try {
33 callbacks[i]();
34 } catch (e) {
35 // Throw the error later for debuging.
36 (function (e) {
37 setTimeout(function () {
38 throw e;
39 });
40 })(e);
41 }
42 }
43 }
44};
45
46/**
47 * Check whether the controller is canceled.
48 *
49 * @returns {boolean} Returns `true` if the controller is canceled, otherwise `false` is returned.
50 */
51CancelController.prototype.isCanceled = function () {
52 return this.canceled;
53};
54
55/**
56 * Register a callback, which will be called when the `cancel()` method is called.
57 *
58 * @param {Function} callback The callback function to call on cancel.
59 */
60CancelController.prototype.registerCancelCallback = function (callback) {
61 if (isFunction(callback)) {
62 this.callbacks.push(callback);
63 }
64};
65
66module.exports = CancelController;