简介
使多个对象都有机会处理请求,从而避免了请求的发送者与多个接受者直接的耦合关系,将这些接受者链接成 一条链,顺着这条链传递该请求,直到找到能处理请求的对象。
问题
btn.onclick = function () {
if (input.value.length === 0) {
console.log("这里不能为空");
} else {
if (Number.isNaN(+input.value)) {
console.log("这里必须是数字");
} else {
if (input.value.length < 6) {
console.log("这里数字长度必须大于6");
}
}
}
};
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>迭代器模式</title>
</head>
<body>
<input type="text" id="input" />
<button id="btn">注册</button>
<script>
/*
使多个对象都有机会处理请求,从而避免了请求的发送者与多个接受者直接的耦合关系,将这些接受者链接成
一条链,顺着这条链传递该请求,直到找到能处理请求的对象
*/
// btn.onclick = function () {
// checks.check();
// };
// function checkEmpty() {
// if (input.value.length === 0) {
// console.log("这里不能为空");
// return;
// }
// }
// function checkNumber() {
// if (Number.isNaN(+input.value)) {
// console.log("这里必须是数字");
// }
// }
// function checkLength() {
// if (input.value.length < 6) {
// console.log("这里数字长度必须大于6");
// }
// }
// class Chain {
// constructor(fn) {
// this.checkRule = fn;
// this.nextRule = null;
// }
// addRule(nextRule) {
// this.nextRule = nextRule;
// }
// check() {
// this.checkRule() === "next" ? this.nextRule.check() : null;
// }
// }
// const checks = new Chain(checkEmpty);
// const checkNumberChain = new Chain(checkNumber);
// const checkLengthChain = new Chain(checkLength);
// checks.addRule(checkNumberChain);
// checks.addRule(checkLengthChain);
// checks.addRule(() => {
// check: () => "end";
// });
//优化
btn.onclick = function () {
checks.check();
};
function checkEmpty() {
if (input.value.length === 0) {
console.log("这里不能为空");
return;
}
}
function checkNumber() {
if (Number.isNaN(+input.value)) {
console.log("这里必须是数字");
}
}
function checkLength() {
if (input.value.length < 6) {
console.log("这里数字长度必须大于6");
}
}
class Chain {
constructor(fn) {
this.checkRule = fn;
this.nextRule = null;
}
addRule(nextRule) {
this.nextRule = new Chain(nextRule);
return this.nextRule;
}
end() {
this.nextRule = {
check: () => "end",
};
}
check() {
this.checkRule() === "next" ? this.nextRule.check() : null;
}
}
const checks = new Chain(checkEmpty);
checks.addRule(checkNumber).addRule(checkLength).end();
</script>
</body>
</html>