Adam Shaw 8 лет назад
Родитель
Сommit
8c62efe870
1 измененных файлов с 68 добавлено и 34 удалено
  1. 68 34
      src/common/TaskQueue.js

+ 68 - 34
src/common/TaskQueue.js

@@ -1,36 +1,69 @@
 
 
-function TaskQueue() {
-	var _this = this;
-	var isPaused = false;
-	var isRunning = 0;
-	var q = [];
-
-	$.extend(this, EmitterMixin);
-
-	this.queue = function(/* taskFunc, taskFunc... */) {
-		q.push.apply(q, arguments); // append
-		tryStart();
-	};
-
-	this.pause = function() {
-		isPaused = true;
-	};
-
-	this.resume = function() {
-		isPaused = false;
-		tryStart();
-	};
-
-	function tryStart() {
-		if (!isRunning && !isPaused && q.length) {
-			isRunning = true;
-			_this.trigger('start');
-			runNext();
+var TaskQueue = Class.extend(EmitterMixin, {
+
+	q: null,
+	isPaused: false,
+	isRunning: false,
+
+
+	constructor: function() {
+		this.q = [];
+	},
+
+
+	queue: function(/* taskFunc, taskFunc... */) {
+		this.q.push.apply(this.q, arguments); // append
+		this.tryStart();
+	},
+
+
+	pause: function() {
+		this.isPaused = true;
+	},
+
+
+	resume: function() {
+		this.isPaused = false;
+		this.tryStart();
+	},
+
+
+	tryStart: function() {
+		if (this.canStart()) {
+			this.start();
 		}
 		}
-	}
+	},
 
 
-	function runNext() { // does not check for empty q
-		var taskFunc = q.shift();
+
+	canStart: function() {
+		return !this.isRunning && this.canRunNext();
+	},
+
+
+	canRunNext: function() {
+		return !this.isPaused && this.q.length;
+	},
+
+
+	start: function() { // does not check canStart
+		this.isRunning = true;
+		this.trigger('start');
+		this.runNext();
+	},
+
+
+	runNext: function() { // does not check for empty q
+		this.runTask(this.q.shift());
+	},
+
+
+	runTask: function(task) {
+		this.runTaskFunc(task);
+	},
+
+
+	runTaskFunc: function(taskFunc) {
+		var _this = this;
 		var res = taskFunc();
 		var res = taskFunc();
 
 
 		if (res && res.then) {
 		if (res && res.then) {
@@ -41,15 +74,16 @@ function TaskQueue() {
 		}
 		}
 
 
 		function done() {
 		function done() {
-			if (!isPaused && q.length) {
-				runNext();
+			if (_this.canRunNext()) {
+				_this.runNext();
 			}
 			}
 			else {
 			else {
-				isRunning = false;
+				_this.isRunning = false;
 				_this.trigger('stop');
 				_this.trigger('stop');
 			}
 			}
 		}
 		}
 	}
 	}
-}
+
+});
 
 
 FC.TaskQueue = TaskQueue;
 FC.TaskQueue = TaskQueue;