Last active
August 29, 2015 14:17
-
-
Save opsb/1a0f20961b2d8713986f to your computer and use it in GitHub Desktop.
Operation processor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var OperationQueue = Class.extend({ | |
| init: function(){ | |
| Evented.extend(this); | |
| this._queue = []; | |
| }, | |
| process: function(operation){ | |
| this._queue.add(operation); | |
| this.emit("operationAdded"); | |
| }, | |
| find: function(callback){ | |
| this._queue.forEach(function(operation){ | |
| if(callback(operation)) return operation; | |
| }); | |
| } | |
| }); | |
| var OperationBatcher = Class.extend({ | |
| previous: null, | |
| init: function(queue){ | |
| this._queue = queue; | |
| }, | |
| pull: function(){ | |
| var operation = this._findNext(); | |
| this.previous = operation; | |
| return operation; | |
| }, | |
| _findNext: function() { | |
| if(!previous) return this._queue.pop(); | |
| this._queue.find(function(operation){ | |
| if(operation.relatedTo(this.previous)) return operation; | |
| }); | |
| return this._queue.pop(); | |
| } | |
| }); | |
| var OperationProcessor = Class.extend({ | |
| init: function(target, supplier){ | |
| this._target = target; | |
| this._supplier = supplier; | |
| }, | |
| onOperationAdded: function(){ | |
| if(!this.currentOperation){ | |
| this.processNext(); | |
| } | |
| } | |
| processNext: function(){ | |
| this.currentOperation = this._supplier.pull(); | |
| if(this.currentOperation){ | |
| this._target.transform(operation).then(function(){ | |
| this.currentOperation = null; | |
| this.processNext(); | |
| }); | |
| } | |
| } | |
| }); | |
| var queue = new OperationQueue(); | |
| var batcher = new OperationBatcher(queue); | |
| var processor = new OperationProcessor(targetTransformable, batcher); | |
| queue.on("operationAdded", processor.onOperationAdded); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment