better displayName Event

This commit is contained in:
Daniel Lugo 2020-02-20 18:51:23 -04:00
parent fba877e814
commit 4f81b8f6b8

View file

@ -185,30 +185,52 @@ const onCurrentHandshakeAddress = (cb, user) => {
}) })
} }
/** @type {Set<(dn: string|null) => void>} */
const dnListeners = new Set()
/** @type {string|null} */
let currentDn = null
const getDisplayName = () => currentDn
/** @param {string|null} dn */
const setDn = dn => {
currentDn = dn
dnListeners.forEach(l => l(currentDn))
}
let dnSubbed = false
/** /**
* @param {(displayName: string|null) => void} cb * @param {(displayName: string|null) => void} cb
* @param {UserGUNNode} user Pass only for testing purposes. * @param {UserGUNNode} user Pass only for testing purposes.
* @throws {Error} If user hasn't been auth. * @throws {Error} If user hasn't been auth.
* @returns {void} * @returns {() => void}
*/ */
const onDisplayName = (cb, user) => { const onDisplayName = (cb, user) => {
if (!user.is) { if (!user.is) {
throw new Error(ErrorCode.NOT_AUTH) throw new Error(ErrorCode.NOT_AUTH)
} }
const callb = debounce(cb, DEBOUNCE_WAIT_TIME) cb(currentDn)
// Initial value if display name is undefined in gun dnListeners.add(cb)
callb(null)
user if (!dnSubbed) {
.get(Key.PROFILE) dnSubbed = true
.get(Key.DISPLAY_NAME) user
.on(displayName => { .get(Key.PROFILE)
if (typeof displayName === 'string' || displayName === null) { .get(Key.DISPLAY_NAME)
callb(displayName) .on(displayName => {
} if (typeof displayName === 'string' || displayName === null) {
}) setDn(displayName)
}
})
}
return () => {
dnListeners.delete(cb)
}
} }
/** /**
@ -555,5 +577,6 @@ module.exports = {
onBio, onBio,
onSeedBackup, onSeedBackup,
onChats, onChats,
getAvatar getAvatar,
getDisplayName
} }