注:这篇文是根据书中的一些片段组合而成的。
观察者模式很久以前有点了解,但是用的地方很少,以至于没有去认真研究。最近在看vue框架,涉及很多观察者模式的应用,趁这个机缘研究一下。这是第一版,随着时间时时更新。
————————————————————————————
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <div> <span style="background:red">ID:xx</span> <span>消息:</span> <span id="msg_num">0</span> </div> <div> <h3>留言显示:</h3> <ul id="msg"> </ul> </div> <div> <textarea rows="5" id="user_input"> </textarea> <br /> <button id="user_submit">发布留言</button> </div> <script> var Observer = (function () { var _message = {}; return { regist: function (type, fn) { if (typeof _message[type] === 'undefined') { _message[type] = [fn]; } else { _message[type].push(fn); } }, fire: function (type, args) { if (!_message[type]) { return; } var events = { type: type, args: args || {} }, len = _message[type].length; for (var i = 0; i < len; i++) { _message[type][i].call(this, events); } }, remove: function (type, fn) { if (_message[type] instanceof Array) { var i = _message[type].length - 1; for (; i >= 0; i--) { _message[type][i] === fn && _message[type].splice(i, 1); } } }, getMessage: function () { return _message; } } })(); //$ function $(id) { return document.getElementById(id); } //工程师A (function () { function addMsgItem(e) { var text = e.args.text; ul = $('msg'), var li = document.createElement("li"); span = document.createElement("span"); li.innerHTML = text; span.innerHTML = "删除"; span.onclick = function () { ul.removeChild(li); Observer.fire('removeCommentMessage', { num: -1 }) } li.appendChild(span); ul.appendChild(li); } Observer.regist("addCommentMessage", addMsgItem); })(); //工程师B (function () { function changeMsgNum(e) { var num = e.args.num; $('msg_num').innerHTML = parseInt($('msg_num').innerHTML) + num; } Observer.regist('addCommentMessage', changeMsgNum); Observer.regist("removeCommentMessage", changeMsgNum); })(); //工程师C (function () { $("user_submit").onclick = function () { var text = $('user_input'); if (text.value === '') { return; } Observer.fire('addCommentMessage', { text: text.value, num: 1 }); text.value = ''; } })(); </script> </body> </html>