From 3ed4e82445e918c3f7892a740e0607f62acb7975 Mon Sep 17 00:00:00 2001 From: chenyongli Date: Tue, 25 Jun 2019 01:10:13 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=97=A5=E8=AE=B0-=E5=B9=BF?= =?UTF-8?q?=E5=B7=9E=E9=98=BF=E5=88=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Observer.js | 48 ++++++++++++++++++++++++++++++ index.html | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 134 insertions(+) create mode 100644 Observer.js create mode 100644 index.html diff --git a/Observer.js b/Observer.js new file mode 100644 index 0000000..cc5d5db --- /dev/null +++ b/Observer.js @@ -0,0 +1,48 @@ +// 将观察者放在闭包中,当页面加载就立即执行 +var Observer = (function(){ + // 防止消息队列暴漏而被篡改故将消息容器作为静态私有变量保存 + var __messages = {}; + return { + // 注册信息接口 + regist : function (type, fn){ + // 如果些消息不存在则应该创建一个该消息类型 + if(typeof __messages[type] === 'undefined'){ + __messages[type] = [fn]; + } else { + // 将动作推入到消息对应的动作执行队列中 + __messages[type].push(fn); + } + }, + // 发布信息接口 + fire : function(type, args){ + // 如果消息没有被注册,则返回 + if(!__messages[type]){ + return; + } + // 定义消息信息 + var events = { + type : type, + args : args || {} + }, + i = 0, + len = __messages[type].length; + // 遍历消息动作 + for(; i < len; i++){ + // 依次执行注册的消息对应的动作序列 + __messages[type][i].call(this, events); + } + }, + // 移除信息接口 + remove : function(type, fn){ + // 如果消息动作队列存在 + if(__messages[type] instanceof Array){ + // 从最后一个消息动作遍历 + var i = __messages[type].length - 1; + for(; i >= 0; i--) { + // 如果存在该动作则在消息动作序列中移除相应动作 + __messages[type][i] === fn && __messages[type].splice(i, 1); + } + } + } + } +})() \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..60e208a --- /dev/null +++ b/index.html @@ -0,0 +1,86 @@ + + + + + + + My diary + + + + + + + \ No newline at end of file