美文网首页
【微信小程序】页面间事件传递

【微信小程序】页面间事件传递

作者: 大Q本Q | 来源:发表于2019-07-05 17:37 被阅读0次
//event.js
/**
 * 作用:通过类似vue组件间事件传递的方式,在小程序中跨页面传递事件
 * 注意:page中订阅on了以后,一定要在onUnload中注销相应订阅
 * 示例:
 *  1. app.js
 *      const EVENT = require('./utils/event')
 *      App({
 *          event: new EVENT()
 *      })
 *  2. 在接收event的page
 *      var app = getApp();
 *      Page({
 *          onLoad:function(){
 *              app.event.on('onAuthUser', this.onAuthUser, this)
 *          },
 *          onAuthUser(){
 *              // auth code
 *          },
 *          // !!!!!!! 一定要在onUnload时注销 !!!!!!!
 *          onUnload:function(){
 *              app.event.off();                         // remove all
 *              app.event.off('onAuthUser');                // remove all callback
 *              app.event.off('onAuthUser',this.onAuthUser);    // remove specific callback
 *          }
 *      })
 * 
 *  2. 在触发event的page
 *      var app = getApp();
 *      Page({
 *          emitAuthUser(){
 *              // code
 *              app.event.emit('onAuthUser',params)
 *          },
 *      })
 */
class EVENT {
    on(event, fn, ctx) {
        if (typeof fn != "function") {
            console.error('fn must be a function')
            return
        }

        this._stores = this._stores || {}

        ;
        (this._stores[event] = this._stores[event] || []).push({
            cb: fn,
            ctx: ctx
        })
    }
    emit(event) {
        this._stores = this._stores || {}
        var store = this._stores[event],
            args
        if (store) {
            store = store.slice(0)
            args = [].slice.call(arguments, 1)
            for (var i = 0, len = store.length; i < len; i++) {
                store[i].cb.apply(store[i].ctx, args)
            }
        }
    }
    off(event, fn) {
        this._stores = this._stores || {}
        // all
        if (!arguments.length) {
            this._stores = {}
            return
        }
        // specific event
        var store = this._stores[event]
        if (!store) return
        // remove all handlers
        if (arguments.length === 1) {
            delete this._stores[event]
            return
        }
        // remove specific handler
        var cb
        for (var i = 0, len = store.length; i < len; i++) {
            cb = store[i].cb
            if (cb === fn) {
                store.splice(i, 1)
                break
            }
        }
        return
    }
}

module.exports =EVENT

相关文章

网友评论

      本文标题:【微信小程序】页面间事件传递

      本文链接:https://www.haomeiwen.com/subject/vnoehctx.html