Skip to content

Instantly share code, notes, and snippets.

@FaiChou
Last active April 3, 2018 15:02
Show Gist options
  • Save FaiChou/62bfbc19752b98b42199978137358749 to your computer and use it in GitHub Desktop.
Save FaiChou/62bfbc19752b98b42199978137358749 to your computer and use it in GitHub Desktop.
A javascript notification for react-native
// FaiChou
// willMount add
// willUnmount remove
const __notices = []; // eslint-disable-line
const isDebug = true;
// register notification,name: notification name,selector: function for action to do,observer: type Object
export const addNotification = (name, selector, observer) => {
if (name && selector) {
if (!observer) {
console.warn('addNotification Warning: need observer');
}
if (isDebug) {
console.log('addNotification:', name);
}
addNotices({
name,
selector,
observer,
});
} else {
console.error('addNotification error: lack of name or selector');
}
};
const addNotices = (newNotice) => {
__notices.push(newNotice);
};
// remove notification, name: notification name,observer: the object who registed it
export const removeNotification = (name, observer) => {
for (let i = 0; i < __notices.length; i++) {
const notice = __notices[i];
if (notice.name === name) {
if (notice.observer === observer) {
__notices.splice(i, 1);
return;
}
}
}
};
// brodcast / send event, name: notification name, info: some params to pass
export const postNotification = (name, info={}) => {
if (__notices.length === 0) {
console.error('postNotification error: no notice');
return;
}
for (let i = 0; i < __notices.length; i++) {
const notice = __notices[i];
if (notice.name === name) {
notice.selector(info);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment