小程序全局事件監(jiān)聽及觸發(fā)使用
解決app.globalData 全局變量更新觸發(fā)頁面及組件更新
創(chuàng)建目錄:utils/events.js
var event = {};
const $on = function(params) {
if (!params) {
return false;
}
if (!params.name) {
console.error("事件監(jiān)聽未設(shè)置名稱 屬性key=name");
return false;
}
if (!params.success) {
console.error("事件監(jiān)聽未設(shè)置回調(diào)函數(shù) 屬性key=success");
return false;
}
if (!params.tg) {
console.error("事件監(jiān)聽未設(shè)置目標對象 屬性key=tg");
return false;
}
if (event[params.name]) {
var list = event[params.name];
list.push([params.tg, params.success]);
} else {
event[params.name] = [
[params.tg, params.success]
];
}
pageStatus(params.tg);
}
const $emit = function(params) {
if (!params) {
return false;
}
if (!params.name) {
console.error("事件發(fā)送未設(shè)置名稱 屬性key=name");
return false;
}
if (event[params.name]) {
var list = event[params.name];
list.forEach(item => {
item[1].call(item[0], params.data);
})
}
}
const $remove = function(params) {
if (!params) {
return false;
}
if (!params.tg) {
console.error("事件監(jiān)聽未設(shè)置目標對象 屬性key=tg");
return false;
}
if (params.name && event[params.name]) {
event[params.name] = event[params.name].filter(a => {
return a[0] != params.tg;
})
} else {
for (let key in event) {
event[key] = event[key].filter(a => {
return a[0] != params.tg;
})
}
}
}
const pageStatus = function(self) {
if (self["onUnload"]) {
var s = self["onUnload"];
self["onUnload"] = function(a) {
s.call(this, a);
$remove({
tg: this
});
}
} else {
self["onUnload"] = function() {
$remove({
tg: this
});
}
}
}
exports.$on = $on;
exports.$emit = $emit;
exports.$remove = $remove;
使用:監(jiān)聽全局事件
import event from '../../utils/events.js'
Component(
{
lifetimes: {
attached: function() {
const that = this
let voiceState = getApp().globalData.voiceState
this.setData({ voiceState })
event.$on({
name: 'changeVoice',
tg: this,
success: (voiceState) => {
that.setData({ voiceState })
}
})
},
},
})
使用: 觸發(fā)全局事件
<text
class="iconfont {{voiceState ? 'icon-shengyinkai' : 'icon-jingyin'}} video-voice"
bind:tap="triggerVoice"></text>
import event from '../../utils/events.js'
pages({
methods: {
triggerVoice() {
app.globalData.voiceState = !app.globalData.voiceState
event.$emit({
name: 'changeVoice',
data: app.globalData.voiceState
})
}
}
})