Merge pull request #474 from nofficalfs/PR-Branch

[Enhancement] `lib.announce`机制改变
This commit is contained in:
Spmario233 2023-10-05 20:20:32 +08:00 committed by GitHub
commit 5ca8769a1e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 41 additions and 37 deletions

View File

@ -337,47 +337,50 @@
}],
},
announce:{
//推送一个对象给所有监听了key的订阅者。
publish:function(key,obj){
if(!_status.announce)return;
if(!_status.announce[key])return;
for(let subscriber of _status.announce[key]){
if(subscriber.onReceive){
subscriber.onReceive(key,obj);
init(){
_status._announce=document.createElement("Announce");
_status._announce_cache=new Map();
delete lib.announce.init;
},
//推送一个对象给所有监听了name的订阅者。
publish(name,values){
if(_status._announce) _status._announce.dispatchEvent(new CustomEvent(name,{
detail:values
}));
return values;
},
//订阅name相关的事件。
subscribe(name,method){
if(_status._announce&&_status._announce_cache) {
let subscribeFunction;
if(_status._announce_cache.has(method)){
let records=_status._announce_cache.get(method);
subscribeFunction=records.get("Listener");
records.get("EventTargets").add(name);
}
}
},
//订阅key相关的事件。
subscribe:function(key,subscriber){
if(typeof subscriber === 'function'){
let subs = {
onReceive:subscriber,
priority:0,
};
subscriber = subs;
}
if(!_status.announce)_status.announce = {};
if(!Array.isArray(_status.announce[key]))_status.announce[key] = [];
var inserted = false;
for(let i=0;i<_status.announce[key].length;i++){
let pri = _status.announce[key][i].priority;
if(pri <= subscriber.priority){
_status.announce[key].splice(i,0,subscriber);
inserted = true;
break;
else{
subscribeFunction=event=>method(event.detail);
let records=new Map();
records.set("Listener",subscribeFunction);
records.set("EventTargets",[name]);
_status._announce_cache.set(method,records);
}
_status._announce.addEventListener(name,subscribeFunction);
}
if(!inserted){
_status.announce[key].push(subscriber);
return method;
},
//取消对事件name的订阅
unsubscribe(name,method){
if(_status._announce&&_status._announce_cache&&_status._announce_cache.has(method)){
let records=_status._announce_cache.get(method);
const listener=records.get("Listener");
let eventTargets=records.get("EventTargets");
eventTargets.remove(name);
if(eventTargets.length<=0) _status._announce_cache.remove(method);
_status._announce.removeEventListener(name,listener);
}
return subscriber;
},
//取消对事件key的订阅subscriber需要为上面lib.announce.subscribe返回的值。
unsubscribe:function(key,subscriber){
if(!_status.announce)return;
if(!_status.announce[key])return;
_status.announce[key].remove(subscriber);
},
return method;
}
},
objectURL:new Map(),
hookmap:{},
@ -9183,6 +9186,7 @@
window.game=game;
game.dynamicStyle.init();
lib.announce.init();
// node:path library alternative
if (typeof module!="object"||typeof module.exports!="object") lib.init.js(`${lib.assetURL}game`,"path",()=>{
lib.path=window._noname_path;