javascript & global event & custom event
阅读原文时间:2023年07月12日阅读:1

javascript & global event & custom event

new CustomEvent object

let event = new CustomEvent(
    "newMessage",
    {
        detail: {
            message: "Hello World!",
            time: new Date(),
        },
        bubbles: true,
        cancelable: true
    }
);

// global html
document.querySelector(`:root`).dispatchEvent(event);
// document.querySelector(`html`).dispatchEvent(event);
// document.querySelector(`body`).dispatchEvent(event);

document.addEventListener("newMessage", newMessageHandler, false);

https://www.sitepoint.com/javascript-custom-events/

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 *
 * @description customizeEvent
 * @augments
 * @example
 * @link
 *
 */

// elements
let body = document.body;
let msgbox = document.getElementById("msgbox");
let log = document.getElementById("log");

// form submit handler
msgbox.addEventListener("submit", SendMessage, false);

// newMessage event subscribers
document.addEventListener("newMessage", newMessageHandler, false);
body.addEventListener("newMessage", newMessageHandler, false);
msgbox.addEventListener("newMessage", newMessageHandler, false);

// newMessage event handler
function newMessageHandler(e) {
    LogEvent(
        "Event subscriber on "
        +
        e.currentTarget.nodeName
        +
        ", "
        +
        e.detail.time.toLocaleString()
        +
        ": "
        +
        e.detail.message
    );
}

// log event in console
function LogEvent(msg) {
    log.textContent += msg + "\n";
    let ot = log.scrollHeight - log.clientHeight;
    if (ot > 0) log.scrollTop = ot;
}

// new message: raise newMessage event
function SendMessage(e) {
    e.preventDefault();
    let msg = document.getElementById("msg").value.trim();
    if (msg && window.CustomEvent) {
        let event = new CustomEvent("newMessage", {
            detail: {
                message: msg,
                time: new Date(),
            },
            bubbles: true,
            cancelable: true
        });
        e.currentTarget.dispatchEvent(event);
    }
}

// const customizeEvent = (datas = [], debug = false) => {
//     let result = ``;
//     // do something...
//     return result;
// };

// export default customizeEvent;

// export {
//     customizeEvent,
// };

old way

  1. A get data, then set global flag = true

  2. B setInterval, listen the global = true, then show data and set the global flag = true


OK

A page

    window.IS_NEW_MSG = false;
    const autoRefreshEvent = (msg = ``) => {
        let event = new CustomEvent("newMessage", {
            detail: {
                message: msg,
                time: new Date().getTime(),
            },
            bubbles: true,
            cancelable: true,
        });
        document.querySelector(`html`).dispatchEvent(event);
        log(`%c dispatchEvent`, `color: red;`, event);
        // document.querySelector(`:root`).dispatchEvent(event);
        // e.currentTarget.dispatchEvent(event);
        window.IS_NEW_MSG = true;
    };




    const handleSelfNewMessage = (obj = {}, debug = false) => {
        log(`Self Messages =`, JSON.stringify(obj, null, 4));
        let chat_list_uids = JSON.parse(window.localStorage.getItem(`chat_list_uids`));
        // log(`chat_list_uids =`, chat_list_uids);
        if (chat_list_uids.length) {
            window.DB = window.DB || {};
            window.DB_SELF = window.DB_SELF || {};
            chat_list_uids.forEach(
                (item, i) => {
                    window.DB[item] = window.DB[item] || [];
                    // DB Store
                    window.DB_SELF[item] = window.DB_SELF[item] || [];
                }
            );
        }
        if (Object.keys(obj).length) {
            let {
                SendUserID: senderUid,
                ReciveUserID: receiverUid,
                SerialNumber: serialNum,
                MsgID: msgId,
                Info: text,
                // MsgType: msgType,
                SendTime: time,
                UnReadMsgCount: count,
                OriginTime: timestamp,
            } = obj;
            let temp = {
                senderUid,
                receiverUid,
                serialNum,
                msgId,
                // msgType,
                text,
                time,
                count,
                isSelf: true,
                timestamp,
            };
            // if (window.DB_SELF[receiverUid]) {
            //     window.DB_SELF[receiverUid] = window.DB_SELF[receiverUid];
            // } else {
            //     window.DB_SELF[receiverUid] = [];
            // }
            log(`window.DB_SELF `, window.DB_SELF, receiverUid),
            window.DB_SELF[receiverUid] = window.DB_SELF[receiverUid] || [];
            log(`window.DB_SELF `, window.DB_SELF, receiverUid),
            window.DB_SELF[receiverUid].push(temp);
            let newsList = window.DB_SELF[receiverUid];
            log(`DB_SELF old`, newsList);
            window.DB_SELF[receiverUid] = getUniqueObjects(newsList, `msgId`);
            log(`DB_SELF new`, window.DB_SELF[receiverUid]);
            // window.DB[receiverUid].push(temp);
            // let newsList = window.DB[receiverUid];
            // log(`news list old`, newsList);
            // window.DB[receiverUid] = getUniqueObjects(newsList, `msgId`);
            // log(`news list new`, window.DB[receiverUid]);
        }
        // delay update
        // window.IS_NEW_MSG = true;
        // autoSetRedPoint();
        autoRefreshEvent();
    };

B page

// let log = console.log;

    newMessageHandler(e) {
        this.autoShowMessage();
        log(`%c receiverNewMessage`, `color: green;`, e);
    },

   document.addEventListener("newMessage", this.newMessageHandler, false);


xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器