Skip to content

Instantly share code, notes, and snippets.

@zhiqiang21
Created April 13, 2017 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhiqiang21/8496b15919b32c5fceae3bb809b1c217 to your computer and use it in GitHub Desktop.
Save zhiqiang21/8496b15919b32c5fceae3bb809b1c217 to your computer and use it in GitHub Desktop.
next 中间件模式的实现
function Middleware() {
this.cache = [];
this.options = null; // 缓存options
}
Middleware.prototype.use = function (fn) {
if (typeof fn !== 'function') {
throw 'middleware must be a function';
}
this.cache.push(fn);
return this;
};
Middleware.prototype.next = function (fn) {
if (this.middlewares && this.middlewares.length > 0) {
var ware = this.middlewares.shift();
ware.call(this, this.options, this.next.bind(this)); // 传入options与next
}
};
/**
* @param options 数据的入口
* @param next
*/
Middleware.prototype.handleRequest = function (options) {
this.middlewares = this.cache.map(function (fn) {
return fn;
});
this.options = options; // 缓存数据
this.next();
};
function validate(options, next) {
console.log('validate', options.data);
next(); // 通过验证
}
function send(options, next) {
setTimeout(function () { // 模拟异步
console.log('send', options.data);
options.url = 'www.baidu.com'; // 设置跳转的url
next();
}, 100);
}
function goTo(options) {
console.log('goTo', options.url);
}
var submitForm = new Middleware();
submitForm.use(validate).use(send).use(goBack);
submitForm.handleRequest({ data: { name: 'xiaoxiong', age: 20 } });
// 结果:
// validate Object {name: "xiaoxiong", age: 20}
//
// send Object {name: "xiaoxiong", age: 20}
// goTo www.baidu.com
submitForm.handleRequest({ data: { name: 'xiaohong', age: 21 } }); // 触发第二次,改变数据内容
// 结果:
// validate Object {name: "xiaohong", age: 21}
//
// send Object {name: "xiaohong", age: 21}
// goTo www.baidu.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment