觀察者模式 發佈&訂閱 一對多 示例:點好咖啡之後坐等被叫 傳統 UML 類圖 javascript 中的 UML 類圖 應用場景 網頁事件綁定 promise jQuery callback nodejs 自定義事件 nodejs 處理文件 其他應用場景 nodejs 中:處理 http 請求,多 ...
觀察者模式
發佈&訂閱
一對多
示例:點好咖啡之後坐等被叫
傳統 UML 類圖
javascript 中的 UML 類圖
應用場景
網頁事件綁定
<button id="btn1"></button>
<script>
$("#btn1").click(function() {
console.log(1);
});
$("#btn1").click(function() {
console.log(2);
});
$("#btn1").click(function() {
console.log(3);
});
</script>
promise
function loadImg(src) {
var promise = new Promise(function(reslove, reject) {
var img = document.creatElement("img");
img.onload = function() {
reslove(img);
};
img.src = src;
});
return promise;
}
var src = ".....";
var result = loadImg(src);
result
.then(function(img) {
console.log("img.width", img.width);
return img;
})
.then(function(img) {
console.log("img.height", img.height);
})
.catch(function(ex) {
console.log(ex);
});
jQuery callback
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<p>jQuery callbacks</p>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var callbacks = $.Callbacks(); // 註意大小寫
callbacks.add(function(info) {
console.log("fn1", info);
});
callbacks.add(function(info) {
console.log("fn2", info);
});
callbacks.add(function(info) {
console.log("fn3", info);
});
callbacks.fire("gogogo");
callbacks.fire("fire");
</script>
</body>
</html>
nodejs 自定義事件
const EventEmitter = require("events").EventEmitter;
const emitter1 = new EventEmitter();
emitter1.on("some", () => {
// 監聽 some 事件
console.log("some event is occured 1");
});
emitter1.on("some", () => {
// 監聽 some 事件
console.log("some event is occured 2");
});
// 觸發 some 事件
emitter1.emit("some");
//------------------------------------------------------------
const emitter = new EventEmitter();
emitter.on("sbowName", name => {
console.log("event occured ", name);
});
emitter.emit("sbowName", "zhangsan"); // emit 時候可以傳遞參數過去
//------------------------------------------------------------
// 任何構造函數都可以繼承 EventEmitter 的方法 on emit
class Dog extends EventEmitter {
constructor(name) {
super();
this.name = name;
}
}
var simon = new Dog("simon");
simon.on("bark", function() {
console.log(this.name, " barked");
});
setInterval(() => {
simon.emit("bark");
}, 500);
nodejs 處理文件
var fs = require("fs");
var readStream = fs.createReadStream("./data/file1.txt"); // 讀取文件的 Stream
var length = 0;
readStream.on("data", function(chunk) {
length += chunk.toString().length;
});
readStream.on("end", function() {
console.log(length);
});
var readline = require("readline");
var fs = require("fs");
var rl = readline.createInterface({
input: fs.createReadStream("./data/file1.txt")
});
var lineNum = 0;
rl.on("line", function(line) {
lineNum++;
});
rl.on("close", function() {
console.log("lineNum", lineNum);
});
其他應用場景
nodejs 中:處理 http 請求,多進程通訊
var http = require("http");
function serverCallback(req, res) {
var method = req.method.toLowerCase(); // 獲取請求的方法
if (method === "get") {
}
if (method === "post") {
// 接收 post 請求的內容
var data = "";
req.on("data", function(chunk) {
// “一點一點”接收內容
console.log("chunk", chunk.toString());
data += chunk.toString();
});
req.on("end", function() {
// 接收完畢,將內容輸出
console.log("end");
res.writeHead(200, { "Content-type": "text/html" });
res.write(data);
res.end();
});
}
}
http.createServer(serverCallback).listen(8081); // 註意埠別和其他 server 的衝突
console.log("監聽 8081 埠……");
// parent.js
var cp = require("child_process");
var n = cp.fork("./sub.js");
n.on("message", function() {
console.log("PARENT got message: " + m);
});
n.send({ hello: "word" });
//sub.js
process.on("message", function() {
console.log("CHILD got message: " + m);
});
process.send({ foo: "bar" });
vue 和 react 組件生命周期出發
class Login extends React.Component {
constructor(props, context) {
super(props, context);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(
this
);
this.state = {
checking: ture
};
}
render() {
return (
<div>
<Header title="開始" history={this.props.history} />
</div>
);
}
componentDidMount() {
// 判斷是否已經登陸
this.doCheck();
}
}
vue watch
var vm = new vue({
el: "#demo",
data: {
firstNameL: "Foo",
lastName: "bar",
fullName: "Foo Bar"
},
watch: {
firstName: function(val) {
this.fullName = val + " " + this.firstName;
},
lastName: function(val) {
this.fullName = this.firstName + " " + val;
}
}
});
設計原則驗證
- 主題和觀察者分離,不是主動觸發而是被動監聽,兩者解耦
- 符合開放和封閉原則