微信小程序开发笔记 进阶篇③——onfire.js事件订阅和发布在微信小程序中的使用

文章目录

  • 一、onfire.js介绍
  • 二、API介绍
  • 三、实例应用
  • 四、onfire源码
  • 五、实例源码

一、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() 取消所有事件订阅

三、实例应用

  • 新建小程序项目
  • 选择JavaScript - 基础模板
  • 导入TDesign - 组件库
  • 导入utils/onfire.js
  • 编写实例应用代码

微信小程序开发笔记 进阶篇③——onfire.js事件订阅和发布在微信小程序中的使用_第1张图片

  • 订阅事件1
  • 异步触发,同步触发,都有回调
  • 取消订阅事件1
  • 触发之后无回调

微信小程序开发笔记 进阶篇③——onfire.js事件订阅和发布在微信小程序中的使用_第2张图片

  • 单次订阅事件2
  • 异步触发,有回调
  • 再触发,无回调

微信小程序开发笔记 进阶篇③——onfire.js事件订阅和发布在微信小程序中的使用_第3张图片

  • 订阅事件1
  • 单次订阅事件2
  • 取消所有订阅
  • 怎么触发,都没有回调

微信小程序开发笔记 进阶篇③——onfire.js事件订阅和发布在微信小程序中的使用_第4张图片

四、onfire源码

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

/**
  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
  };
});

五、实例源码

onfire.js

import Message from 'tdesign-miniprogram/message/index';
var onfire = require("../../utils/onfire.js");

Page({
    data: {},
    onEvent1Btn(e) {
        console.log("订阅事件1")
        onfire.on(
            "event1",
            function (data) {
                console.log("事件1回调,数据=" + data)
                Message.info({
                    offset: [20, 32],
                    duration: 2000,
                    icon: false,
                    content: "事件1回调,数据=" + data,
                });
            }
        )
    },
    unEvent1Btn(e) {
        console.log("取消订阅事件1")
        onfire.un("event1")
    },
    oneEvent2Btn(e) {
        console.log("单次订阅事件2")
        onfire.one(
            "event2",
            function (data) {
                console.log("事件2回调,数据=" + data)
            }
        )
    },
    unEvent2Btn(e) {
        console.log("取消订阅事件2")
        onfire.un("event2")
    },
    clearBtn(e) {
        console.log("取消所有订阅")
        onfire.clear()
    },
    fireEvent1Btn(e) {
        console.log("异步触发事件1(数据123)")
        onfire.fire("event1", 123)
    },
    fireSyncEvent1Btn(e) {
        console.log("同步触发事件1(数据456)")
        onfire.fire("event1", 456)
    },
    fireEvent2Btn(e) {
        console.log("异步触发事件2(数据789)")
        onfire.fire("event2", 789)
    },
    fireSyncEvent2Btn(e) {
        console.log("同步触发事件2(数据012)")
        onfire.fireSync("event2", "012")
    },
});

onfire.json

{
  "navigationBarTitleText": "onfire",
  "navigationBarBackgroundColor": "#fff",
  "usingComponents": {
    "t-button": "tdesign-miniprogram/button/button",
    "t-demo": "../../components/demo-block/index"
  }
}

onfire.wxml

<view class="demo">
  <view class="demo-title">onfire.js view>
  <view class="demo-desc"> 一个简单实用的事件订阅和发布的库。 view>
  
  <t-demo title="订阅">
    <view class="box">
      
      <t-button theme="primary" variant="plain" block bindtap="onEvent1Btn">订阅事件1t-button>
      <t-button theme="plain" variant="plain" block bindtap="unEvent1Btn">取消订阅事件1t-button>
      <t-button theme="primary" variant="plain" block bindtap="oneEvent2Btn">单次订阅事件2t-button>
      <t-button theme="plain" variant="plain" block bindtap="unEvent2Btn">取消订阅事件2t-button>
      <t-button variant="plain" block bindtap="clearBtn">取消所有订阅t-button>
    view>
  t-demo>
  
  <t-demo title="发布">
    <view class="box">
      <t-button theme="primary" block bindtap="fireEvent1Btn">异步触发事件1(数据123)t-button>
      <t-button theme="primary" variant="plain" block bindtap="fireSyncEvent1Btn">同步触发事件1(数据456)t-button>
      <t-button theme="primary" block bindtap="fireEvent2Btn">异步触发事件2(数据789)t-button>
      <t-button theme="primary" variant="plain" block bindtap="fireSyncEvent2Btn">同步触发事件2(数据012)t-button>
    view>
  t-demo>
  <t-message id="t-message" bind:actionBtnClick="clickMessageBtnHadnle" t-class="t-class-content" />
view>

onfire.wxss

page {
  background: #fff;
}
.demo-block__oper {
  padding: 0 32rpx;
}
.button-group {
  margin-top: 32rpx;
}
.button-group .button-group-item {
  margin-bottom: 32rpx;
}

.box {
  margin: 0 32rpx;
}

.demo .t-button {
  margin-top: 32rpx;
}
.demo .full-width {
  background: rgba(0, 0, 0, 0.4);
  padding: 8px 0;
  margin-top: 16px;
}
.demo .full-width .t-button {
  margin-top: 0;
}
.demo .no-border {
  border: 0;
}
.demo .no-border-radius {
  border-radius: 0;
}
.demo .content-margin-right {
  margin-right: 32rpx;
}
.demo .box {
  margin: 0 32rpx;
}
.demo .align-bottom {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
}

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

你可能感兴趣的:(微信小程序开发笔记,javascript,微信小程序,onfire,订阅,发布)