-
-
Save yejinjian/bd845c56ca0afbe8d88b01e7f825b62d to your computer and use it in GitHub Desktop.
A very minimal Javascript (ES5 & ES6) Middleware Pattern Implementation
This file contains 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 Middleware = function() {}; | |
Middleware.prototype.use = function(fn) { | |
var self = this; | |
this.go = (function(stack) { | |
return function(next) { | |
stack.call(self, function() { | |
fn.call(self, next.bind(self)); | |
}); | |
}.bind(this); | |
})(this.go); | |
}; | |
Middleware.prototype.go = function(next) { | |
next(); | |
}; |
This file contains 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
class Middleware { | |
use(fn) { | |
this.go = ((stack) => (next) => stack(() => fn.call(this, next.bind(this))))(this.go); | |
} | |
go = (next) => next() | |
} |
This file contains 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
// Inspired by: https://github.com/kolodny/exercises/tree/master/middleware | |
var middleware = new Middleware(); | |
middleware.use(function(next) { | |
var self = this; | |
setTimeout(function() { | |
self.hook1 = true; | |
next(); | |
}, 10); | |
}); | |
middleware.use(function(next) { | |
var self = this; | |
setTimeout(function() { | |
self.hook2 = true; | |
next(); | |
}, 10); | |
}); | |
var start = new Date(); | |
middleware.go(function() { | |
console.log(this.hook1); // true | |
console.log(this.hook2); // true | |
console.log(new Date() - start); // around 20 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment