一个事件订阅和发布的库(onfire.js)的源码浅析
文章目录
- 一、onfire.js介绍
- 二、API介绍
- 三、变量浅析
- 四、订阅函数浅析
- 五、发布函数浅析
- 六、全部源码
一、onfire.js介绍
一个简单实用的事件订阅和发布的库。
onfire.js 的 github地址
二、API介绍
函数 | 说明 |
---|---|
on(eventName, callback, context)
|
订阅eventName 事件,当事件触发时,回调callback
|
one(eventName, callback, context)
|
订阅eventName 事件,当事件触发时,只回调一次callback
|
fire(eventName)
|
异步触发eventName 事件,将数据发送给回调函数
|
fireSync(eventName)
|
同步触发eventName 事件,将数据发送给回调函数
|
un(event)
|
取消event 事件订阅
|
clear()
|
取消所有事件订阅 |
三、变量浅析
事件列表
var __onfireEvents = {},
四、订阅函数浅析
on
和one
函数基本相似,都是通过调用_bind
函数实现- 不同的地方在于
_bind
函数的第三个参数,实现订阅N次,还是只订阅1次
function on(eventName, callback, context) {return _bind(eventName, callback, 0, context);}
function one(eventName, callback, context) {return _bind(eventName, callback, 1, context);}
_bind
函数先判断__onfireEvents
事件队列中是否已经含有eventName
事件了eventName
作为__onfireEvents
事件队列的索引,存入callback
和is_one
function _bind(eventName, callback, is_one, context) {if (typeof eventName !== string_str || typeof callback !== function_str) {throw new Error('args: '+string_str+', '+function_str+'');}if (! hasOwnKey(__onfireEvents, eventName)) {__onfireEvents[eventName] = {};}__onfireEvents[eventName][++__cnt] = [callback, is_one, context];return [eventName, __cnt];}
五、发布函数浅析
fire
和fireSync
基本相似,都是通过调用_fire_func
函数实现- 不同的地方在于
fire
通过setTimeout
方法实现异步执行,而fireSync
是同步执行,会堵塞后续的函数
function fire(eventName) {// fire eventsvar args = slice(arguments, 1);setTimeout(function () {_fire_func(eventName, args);});}
function fireSync(eventName) {_fire_func(eventName, slice(arguments, 1));}
_bind
函数先判断__onfireEvents
事件队列中是否含有eventName
事件- 然后遍历
__onfireEvents
事件队列,执行回调函数 - 根据
is_one
,决定是否执行后,从__onfireEvents
事件队列中删除该eventName
事件
function _fire_func(eventName, args) {if (hasOwnKey(__onfireEvents, eventName)) {_each(__onfireEvents[eventName], function(key, item) {item[0].apply(item[2], args); // do the functionif (item[1]) delete __onfireEvents[eventName][key]; // when is one, delete it after triggle});}}
六、全部源码
/**Copyright (c) 2016 hustcc http://www.atool.org/License: MIT https://github.com/hustcc/onfire.js
**/
/* jshint expr: true */
!function (root, factory) {if (typeof module === 'object' && module.exports)module.exports = factory();elseroot.onfire = factory();
}(typeof window !== 'undefined' ? window : this, function () {var __onfireEvents = {},__cnt = 0, // evnet counterstring_str = 'string',function_str = 'function',hasOwnKey = Function.call.bind(Object.hasOwnProperty),slice = Function.call.bind(Array.prototype.slice);function _bind(eventName, callback, is_one, context) {if (typeof eventName !== string_str || typeof callback !== function_str) {throw new Error('args: '+string_str+', '+function_str+'');}if (! hasOwnKey(__onfireEvents, eventName)) {__onfireEvents[eventName] = {};}__onfireEvents[eventName][++__cnt] = [callback, is_one, context];return [eventName, __cnt];}function _each(obj, callback) {for (var key in obj) {if (hasOwnKey(obj, key)) callback(key, obj[key]);}}/*** onfire.on( event, func, context ) -> Object* - event (String): The event name to subscribe / bind to* - func (Function): The function to call when a new event is published / triggered* Bind / subscribe the event name, and the callback function when event is triggered, will return an event Object**/function on(eventName, callback, context) {return _bind(eventName, callback, 0, context);}/*** onfire.one( event, func, context ) -> Object* - event (String): The event name to subscribe / bind to* - func (Function): The function to call when a new event is published / triggered* Bind / subscribe the event name, and the callback function when event is triggered only once(can be triggered for one time), will return an event Object**/function one(eventName, callback, context) {return _bind(eventName, callback, 1, context);}function _fire_func(eventName, args) {if (hasOwnKey(__onfireEvents, eventName)) {_each(__onfireEvents[eventName], function(key, item) {item[0].apply(item[2], args); // do the functionif (item[1]) delete __onfireEvents[eventName][key]; // when is one, delete it after triggle});}}/*** onfire.fire( event[, data1 [,data2] ... ] )* - event (String): The event name to publish* - data...: The data to pass to subscribers / callbacks* Async Publishes / fires the the event, passing the data to it's subscribers / callbacks**/function fire(eventName) {// fire eventsvar args = slice(arguments, 1);setTimeout(function () {_fire_func(eventName, args);});}/*** onfire.fireSync( event[, data1 [,data2] ... ] )* - event (String): The event name to publish* - data...: The data to pass to subscribers / callbacks* Sync Publishes / fires the the event, passing the data to it's subscribers / callbacks**/function fireSync(eventName) {_fire_func(eventName, slice(arguments, 1));}/*** onfire.un( event ) -> Boolean* - event (String / Object): The message to publish* When passed a event Object, removes a specific subscription.* When passed event name String, removes all subscriptions for that event name(hierarchy)** Unsubscribe / unbind an event or event object.** Examples** // Example 1 - unsubscribing with a event object* var event_object = onfire.on('my_event', myFunc);* onfire.un(event_object);** // Example 2 - unsubscribing with a event name string* onfire.un('my_event');**/function un(event) {var eventName, key, r = false, type = typeof event;if (type === string_str) {// cancel the event name if existif (hasOwnKey(__onfireEvents, event)) {delete __onfireEvents[event];return true;}return false;}else if (type === 'object') {eventName = event[0];key = event[1];if (hasOwnKey(__onfireEvents, eventName) && hasOwnKey(__onfireEvents[eventName], key)) {delete __onfireEvents[eventName][key];return true;}// can not find this event, return falsereturn false;}else if (type === function_str) {_each(__onfireEvents, function(key_1, item_1) {_each(item_1, function(key_2, item_2) {if (item_2[0] === event) {delete __onfireEvents[key_1][key_2];r = true;}});});return r;}return true;}/*** onfire.clear()* Clears all subscriptions**/function clear() {__onfireEvents = {};}return {on: on,one: one,un: un,fire: fire,fireSync: fireSync,clear: clear};
});
觉得好,就一键三连呗(点赞+收藏+关注)
一个事件订阅和发布的库(onfire.js)的源码浅析相关推荐
- 事件订阅发布 JavaScript 库 onfire.js
onfire.js 详细介绍 onfire.js 是一个很简单的事件分发的Javascript库(仅仅 0.9kb),简洁实用. 可以用于: 简单的事件分发: 在 react / vue.js / a ...
- 微信小程序开发笔记 进阶篇③——onfire.js事件订阅和发布在微信小程序中的使用
文章目录 一.前言 二.onfire.js介绍 三.API介绍 四.实例应用 五.onfire源码 六.实例源码 一.前言 微信小程序开发笔记--导读 二.onfire.js介绍 一个简单实用的事件订 ...
- react相关代码库以及框架的源码解析
持续更新中react相关库源码浅析, react ts3 项目 ???对react相关代码库以及框架的源码进行了一定的分析 ?react16.6 View contents 源码实例分析:可见runl ...
- 微信小程序使用onfire.js(事件订阅和分发JavaScript 库)实现跨页面传参,对onfire的全面了解
开发微信小程序时,页面间数据传送多采用URL方式传参.添加全局变量,对于在本地缓存不大实用(感觉操作缓存,应该性能会有一定的损耗吧).而从新打开的页面回到之前的界面,貌似只有放在本地缓存.添加全局变量 ...
- 横板格斗类游戏实战:事件订阅与发布系统
玩家在游戏战斗过程中,被某个怪物把血打掉了,然后界面上的UI血条的数值就要发生变化,如图: 1.7-1 (如图1.7-1) 按照一般的处理方式,我们在战斗的逻辑里面掉血后,要去找到UI界面中的某个节点 ...
- Android事件分发机制完全解析,带你从源码的角度彻底理解(上)
<div id="container"> <div id="header"> <div class=&qu ...
- libevent源码浅析: http库
libevent自带了一个http库,用它可以很简单的实现一个http服务器,本文非常简单地分析之.evhttp evhttp库有几个主要的结构体,它们之间的联系非常龌龊: 其中,结构体even ...
- 【学习笔记】Keras库下的resnet源码分析
Keras库下的resnet源码应用及解读 其实我也不知道这种东西有没有写下来的必要,但是跑代码的时候总摸鱼总归是不好的.虽然很简单,不过我也大概做个学习记录,写给小白看的.源码来自keras文档,大 ...
- 【转】Android事件分发机制完全解析,带你从源码的角度彻底理解(下)
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/9153761 记得在前面的文章中,我带大家一起从源码的角度分析了Android中Vi ...
最新文章
- 微信无法连接到服务器(110087)),110087无法连接网络是什么意思
- 有感软件安装称呼的变化
- 更安全的Web通信HTTPS
- java antd实现登录,AntDesign(React)学习-4 登录页面提交数据简单实现
- ngx lua API介绍
- onenote 模板_onenote实用?炫酷功能系列篇②:用插件让效率翻倍
- 机器视觉系统工作流程及优势分析
- 计算机网络七版pdf
- CentOS安装jre环境
- pygame基本实现塔防游戏
- 如何让vnc控制由默认的twm界面改为gnome?(转)
- 联合学习 | 纵向LR原理综述
- maven打jar包时报update interval of XXX has elapsed or updates are force
- MBProgressHUD等待框背景色与菊花等待框颜色修改
- 智能时代,三步让自己不再焦虑
- 前端关于获取网络时间的方法 api (直接获取时间戳)
- (更新时间)2021年6月4日 商城高并发秒杀系统(.NET Core版) 30-lua文件封装加载和执行
- mysql多表查询视图_mysql多表查询并创建视图
- 百度地图之自定义绘制功能
- SD-WAN不断冲击传统WAN架构