zoukankan      html  css  js  c++  java
  • 利用观察者模式 进行不同页面的传值

    // 创建文件 observer.js
    const eventMap = {};
    
    //监听事件
    //$on(事件名字, 回调函数1)
    //$on(事件名字, 回调函数2)
    const $on = function(eventName, eventCallback){
        //判断事件是否有对应的装载事件回调的容器
        if(!eventMap[eventName]){
            eventMap[eventName] = [];//没有就创建
        }
        //将事件回调缓存在容器中
        eventMap[eventName].push(eventCallback);
    
    }
    
    
    //触发事件
    //$emit(事件名字, 传递的参数);
    const $emit = function(eventName, params){
    //$emit = function(eventName, ...rest){
        //取得事件所对应的所有回调方法
        let eventList = eventMap[eventName];
        if(!eventList)
            return;
        //遍历所有回调方法
        eventList.map(cb=>{
            cb(params);
    //        cb(...rest);
        })
    }
    
    
    //移除事件
    //$off(eventName);//移除所有监听
    //$off(eventName, callback);//移除指定监听
    const $off = function(eventName, callback){
        //取得事件所对应的所有回调
        let eventList = eventMap[eventName];
        if(!callback){
            //移除所有监听
            eventMap[eventName] = null;
        }else{
            //移除指定监听
            eventMap[eventName] = eventList.filter(cb=>{
                //判断事件是否是需要移除的
                return cb != callback
            })
        }
    }
    
    export default {
        $on,
        $emit,
        $off
    }
    // 需要的页面进行引入
    import observer from '../../utils/observer.js'
    // 监听 observer.$on(
    'calibrationVal', (openId) => { // 获取最近一次检测数据 this.getLatelyData(openId) // 获取最近三天检测数据 this.getThreeData(openId) })
    // 需要的页面进行引入

    import observer from '../../utils/observer.js' //反向传值 //触发监听的事件 observer.$emit('calibrationVal', this.data.openId); wx.navigateBack({ });
  • 相关阅读:
    HTML5新增标签和属性
    HTML——表单标签
    HTML——表格标签
    js
    js
    js
    js
    js-02-2
    js
    selleck --手机端-- 销售打卡记录下载
  • 原文地址:https://www.cnblogs.com/yangzhenhong/p/10955549.html
Copyright © 2011-2022 走看看