一个事件订阅和发布的库(onfire.js)的源码浅析

一、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 = {},

四、订阅函数浅析

  • onone函数基本相似,都是通过调用_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事件队列的索引,存入callbackis_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];
  }

五、发布函数浅析

  • firefireSync基本相似,都是通过调用_fire_func函数实现
  • 不同的地方在于fire通过setTimeout方法实现异步执行,而fireSync是同步执行,会堵塞后续的函数
  function fire(eventName) {
    // fire events
    var 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 function
        if (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();
  else
    root.onfire = factory();
}(typeof window !== 'undefined' ? window : this, function () {
  var __onfireEvents = {},
   __cnt = 0, // evnet counter
   string_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 function
        if (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 events
    var 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 exist
      if (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 false
      return 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
  };
});

觉得好,就一键三连呗(点赞+收藏+关注)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
onfire.js一个很简单的事件分发的Javascript(仅仅 0.9kb),简洁实用。 可以用于: 简单的事件分发; 在 react / vue.js / angular 用于跨组件的轻量级实现; 事件订阅发布; API方法: 1.on(event_name, callback) 绑定事件,参数为event_name和callback, 当有名字为event_name的事件发生的时候,callback方法将会被执行。 这个方法会返回一个eventObj,这个可以用于使用un(eventObj)方法来取消事件绑定。 2.one(event_name, callback) 绑定(订阅事件,参数为 event_name with callback. 当被触发一次之后失效。只能被触发一次,一次之后自动失效。 3.fire(event_name, data) 触发名字为event_name的事件,并且赋予变量data为callback方法的输入值。 4.un(eventObj / eventName / function) 取消事件绑定。可以仅仅取消绑定一个事件回调方法,也可以直接取消全部的事件; 5.clear() 清空所有事件。 使用Demo: 1. 引入js文件 npm install onfire.js 可以使用[removed]标签直接引入; 也可以使用require或者import关键字引入,会得到全局变量 onfire。 import onfire from 'onfire.js'; // or var onfire = require("onfire.js"); 2. 简单使用 使用方法on来订阅事件, 使用un来取消订阅, 使用fire方法来触发事件。 import onfire from 'onfire.js'; // 绑定事件 var eventObj = onfire.on('test_event', function(data) {     console.log('this is a event 1'); }); var eventObj2 = onfire.on('test_event', function(data) {     console.log('this is a event 2'); }); // 触发事件 onfire.fire('test_event', 'test_data'); // 取消绑定 onfire.un(eventObj); // 取消绑定这个事件. onfire.un('test_event'); // 取消绑定所有的 `test_event`. 标签:onfire

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小康师兄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值