Created
April 13, 2017 02:24
-
-
Save zhiqiang21/8496b15919b32c5fceae3bb809b1c217 to your computer and use it in GitHub Desktop.
next 中间件模式的实现
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
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