Function chain isnt working Angular 5 - javascript

Sorry not exactly a function chain but I have this code
ActivityService._hubConnection.on('Send', (activity: ActivityDto) => {
this.activity = activity;
if (activity.title === 'LOGIN') {
this.showActivity(`${activity.user.firstName} ${activity.user.surname} logged in.`);
} else if (activity.title === 'COMMENT') {
this.showActivity(`${activity.user.firstName} ${activity.user.surname} commented on: XB-ID-${activity.messageId}`, `/app/main/dashboard/xpert-detail/${activity.messageId}/comment`, null);
} else if (activity.title === 'ASSIGNED') {
this.showActivity(`${activity.user.firstName} ${activity.user.surname} assigned: XB-ID-${activity.messageId}`, `/app/main/dashboard/xpert-detail/${activity.messageId}/comment`);
} else if (activity.title === 'SYNC COMPLETE') {
this.showActivity(`Sync complete, View Changes`, `/app/main/dashboard/alerts/all`, 'complete');
} else if (activity.title === 'FILE') {
this.showActivity(`${activity.user.firstName} ${activity.user.surname} filed: XB-ID-${activity.messageId}`, `/app/main/dashboard/xpert-detail/${activity.messageId}/comment`)
} else if (activity.title === 'XPERT SYNC') {
this.showActivity(`Sync In Progress.`, `/app/main/dashboard/activity`, 'start' );
}
});
showActivity(popText, notifLink = null, sync = null) {
this.popupText = popText;
if (notifLink !== null) {
this.notifLink = notifLink;
}
if (sync !== null) {
if (sync === 'complete') {
this._activityService.finishSync();
} else if (sync === 'start') {
this._activityService.startSync();
}
}
this.showNotif();
}
showNotif() {
const notif = <HTMLElement>document.querySelector('.notification-tab');
notif.style.display = 'flex';
notif.style.bottom = '0';
setTimeout(() => {
notif.style.bottom = '-50px';
setTimeout(() => {
notif.style.display = 'none';
}, 500);
}, 5000);
}
now I cant figure out why this isnt working, basically what is happening is say im recieving a comment, so the activity.title === 'COMMENT', it should run the showActivity() function, which then should run the showNotif() function, ive put breakpoints on every part of the functions and the breakpoint hits the this.showActivity() but then nothing happens? none of the other breakpoints are hit and I cannot figure out what the problem is! It doesnt make any sense to me.
Any help would be appreciated, I have no idea what could be going wrong...
Thanks

Try to wrap you functions to try.. catch, maybe there is uncatch exception.
showActivity(popText, notifLink = null, sync = null) {
try {
this.popupText = popText;
if (notifLink !== null) {
this.notifLink = notifLink;
}
if (sync !== null) {
if (sync === 'complete') {
this._activityService.finishSync();
} else if (sync === 'start') {
this._activityService.startSync();
}
}
this.showNotif();
} catch (e) {
console.error(e);
}
}
And wrap here too)
if (activity.title === 'COMMENT') {
try {
this.showActivity(`${activity.user.firstName} ${activity.user.surname} commented on: XB-ID-${activity.messageId}`, `/app/main/dashboard/xpert-detail/${activity.messageId}/comment`, null);
} catch (e) {
console.error(e);
}
}

Related

Double click function not working in the React

I have followed this link https://codesandbox.io/s/25777826onclick-works-but-ondoubleclick-is-ignored-on-react-component-ul6f5?file=/src/App.tsx to create a double-click event. This is simple and works. But if I use this method modification to my code is not working.
This one is a sample double-click function:
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
switch (e.detail) {
case 1:
console.log("click");
break;
case 2:
console.log("double click");
break;
case 3:
console.log("triple click");
break;
}
};
<div className="App">
<button onClick={handleClick}>Click me</button>
</div>
This is my original code:
const popUpHandler = e => {
console.log('popUpHandler', e);
if (e.type === 'Editor') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
const doctorFromDb = response.data.doctor;
if (doctorFromDb.includes('|')) {
setStringOfDoctor(doctorFromDb.split('|'));
} else {
setStringOfDoctor([doctorFromDb]);
}
setAppt(response.data);
});
setOpenUpdatePopup(true);
} else if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
if (e.type === 'DeleteAlert') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
setAppt(response.data);
});
setOpenDeletePopup(true);
}
}
if (e.type === 'QuickInfo' && e.target.classList[0] === 'e-work-cells') {
e.cancel = true;
if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
};
This one is after modification to my code, but is not working:
const popUpHandler = (e: React.MouseEvent<HTMLButtonElement>) => {
switch (e.detail) {
case 1:
console.log('Nothing');
break;
case 2:
if (e.type === 'Editor') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
const doctorFromDb = response.data.doctor;
if (doctorFromDb.includes('|')) {
setStringOfDoctor(doctorFromDb.split('|'));
} else {
setStringOfDoctor([doctorFromDb]);
}
setAppt(response.data);
});
setOpenUpdatePopup(true);
} else if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
if (e.type === 'DeleteAlert') {
e.cancel = true;
if (e.data.Id !== undefined) {
getApptDetail(e.data.Id).then(response => {
setAppt(response.data);
});
setOpenDeletePopup(true);
}
}
if (e.type === 'QuickInfo' && e.target.classList[0] === 'e-work-cells') {
e.cancel = true;
if (e.data.StartTime !== undefined) {
setStringOfDoctor([]);
setStartTime(e.data.StartTime);
setDoctorName(e.data.Doctor);
setOpenPopup(true);
}
}
}
};
Hope someone can guide me on how to modify my original code and make it double-click (case 2 is double click). Thank you.

Refactoring if else statement

Here is my method:
Object.entries(query).forEach(([key, value]) => {
if (key === 'team_ids') {
if (typeof value === 'string') {
this.items.push(this.$store.getters.teamById(value));
} else {
value.forEach((itemId) => {
this.items.push(this.$store.getters.teamById(itemId));
});
}
else if (key === 'close_ids') {
if (typeof value === 'string') {
this.items.push(this.$store.getters.closeFriendsById(value));
} else {
value.forEach((friendId) => {
this.items.push(this.$store.getters.closeFriendsById(friendId));
});
}
} else {
if (key === 'name') this.name = value;
if (key === 'patr') this.patr= value;
}
});
I am trying to refactor it but now i'm stumped...
It don't looks good.
Any advice?
You can refactor if statements with a switch statement.
Try this:
Object.entries(query).forEach(([key, value]) => {
switch(key) {
case 'name' :
this.name = value; break;
case 'patr' :
this.patr = value; break;
default:
let getterMap = {
'team_ids': 'teamById',
'close_ids': 'closeFriendsById'
}
if(Array.isArray(value)) {
value.forEach((itemId) => {
this.items.push(this.$store.getters[getterMap[key]](itemId));
});
} else {
this.items.push(this.$store.getters[getterMap[key]](value));
}
break;
}
});
You can add more keys in getterMap if you want to.
It's not bad, You have ternary operators which make code cleaner and if statements are shortened. However, to if you want to refactor it, you should provide some info about the logic, because it is important in refactoring.

parameter.includes() is not a function

I'm pretty new at js programming. I'm developing an admission form as part of our project to be submitted. It's also my first time asking a question here.
I'm creating a form of validation to prevent any invalid values to be entered. I also need some optimizations at my code. If you have any suggestions to make it shorter, I'll be glad to accept your suggestion too.
I tried executing the matchCheck() function on other scenarios, but it just works fine. I also tried executing validateDate() on the console and other scenarios, but it also worked without any errors. I got an error when the functions are executed at if statements.
Here is the error message: Unknown TypeError: arrayToBeChecked.includes is not a function
I got an error at these function and if statements:
function matchCheck(arrayToBeChecked, findingValue) {
return arrayToBeChecked.includes(findingValue);
}
if (matchCheck(date[0], "null") === false)
if (validateDate(bdate) === true)
Here is the code (Excluded some of the unrelated variables and codes):
//Check Match
function matchCheck(arrayToBeChecked, findingValue) {
return arrayToBeChecked.includes(findingValue);
}
//Date Validator
//Expected Format [MM/DD/YYYY]
function validateDate(date) {
//check if the date is valid
var leapYear = date[2] % 4;
var mos31 = ["1", "3", "5", "7", "8", "10", "12"];
var mos30 = ["4", "6", "9", "11"];
var flyInv = ["30", "31"];
var fnlyInv = ["29", "30", "31"];
var mos30Inv = "31";
if (matchCheck(date[0], "null") === false) {
if (matchCheck(date[1], "null") === false) {
if (matchCheck(date[2], "null") === false) {
if (leapYear == 0) {
if (date[0] == "2") {
if (matchCheck(flyInv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else if (matchCheck(mos31, date[0]) === true) {
return true;
}
else if (matchCheck(mos30, date[0]) === true) {
if (matchCheck(mos30Inv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else {
return false
}
}
else {
if (date[0] == "2") {
if (matchCheck(fnlyInv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else if (matchCheck(mos31, date[0]) === true) {
return true;
}
else if (matchCheck(mos30, date[0]) === true) {
if (matchCheck(mos30Inv, date[1]) === false) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
//Contact Number Validator
//Expected Format [09XXXXXXXXX]
function cnValid(nos) {
if (nos.value.length === 11) {
if(nos.indexOf("09") > -1) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
//Check for empty selects
function checkEmptySelects(el) {
var selects = document.querySelectorAll(el);
var i;
for (i = 0; i < selects.length; i++) {
if (selects[i].value == "0") {
return true;
}
else {
return false;
}
}
}
//Valid Relation Values
var vrv = ["mother", "father", "grandmother", "grandfather", "auntie", "uncle", "housemaid", "Mother", "Father", "Grandmother", "Grandfather", "Auntie", "Uncle", "Housemaid", "Aunt", "aunt", "brother", "Brother", "sister", "Sister", "cousin", "Cousin"];
//Start Review
function reviewForm() {
var letters = /^[a-zA-Z\s]*$/;
var mailFormat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var noScFormat = /[^a-zA-Z0-9\\,\\.\s]/g;
//Perform Checks
if (checkEmptySelects("select") === false) {
if (ln.value.match(letters)) {
if (fn.value.match(letters)) {
if (mn.value.match(letters)) {
if (eml.value.match(mailFormat)) {
if (age.value >= 0) {
if (age.value <= 100) {
if (validateDate(bdate) === true) {
if (pob.value.match(noScFormat)) {
if (ca.value.match(noScFormat)) {
if (rlg.value.match(letters)) {
if (nsl.value.match(letters)) {
if (cmn.value.match(letters)) {
if (mo.value.match(letters)) {
if (cfn.value.match(letters)) {
if (fo.value.match(letters)) {
if (gn.value.match(letters)) {
if (matchCheck(vrv, rts) === true) {
if (cnValid(cn) === true) {
if (lrn.value.length === 12) {
//Submit Data to db if all of the requirements are passed.
}
else {
//Error Message;
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
else {
//Error Message
}
}
The error occurs when the "arrayToBeChecked" value that is passed to the "matchCheck()" function is not an arry. To fix this, you could convert "arrayToBeChecked" to an array if it's not already an array.
function matchCheck(arrayToBeChecked, findingValue) {
// Convert arrayToBeChecked to an array if it's not already an array
if (!Array.isArray(arrayToBeChecked)) {
arrayToBeChecked = [arrayToBeChecked];
}
return arrayToBeChecked.includes(findingValue);
}

Is there a way to return a boolean value through setInterval() function?

I'm working on a video player project and I'm using videojs as well as videojs-ima for ad pre-rolls.
I've finally figured out a way to tell if there is an ad present or not; however, I'm trying to return a boolean value of true or false in order to tell when to run and execute a certain code block.
Here's my code, it currently doesn't work like it's purpose to.
if (navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/Android/i)) {
let checkAd = document.querySelectorAll('.ima-ad-container');
let checkAdLoop = setInterval(() => {
for (let i=0; i < checkAd.length; i++) {
if (checkAd[i].style.display == 'none') {
console.log('Ad is NOT playing.');
return false;
} else {
console.log('Ad is playing.');
return true;
// do nothing
}
}
}, 1000);
player.on('touchend', () => {
if (player.paused() && checkAdLoop() == false) {
player.play();
} else if (player.currentTime > 0 && checkAdLoop() == false) {
player.pause();
}
});
$('.vjs-icon-placeholder').on('touchend', () => {
if (player.paused() && checkAdLoop() == false) {
player.play();
} else if (player.currentTime > 0 && checkAdLoop() == false) {
player.pause();
}
});
}
I would love it if someone could please help me understand and could explain to me why this doesn't work. How could I go about fixing this?
I know I'm close. Thanks in advance!
This was a classical XY problem.
Trying to solve a problem that wasn't really related to the overall picture.
Here's the code that works and how I went about it differently.
if (navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/Android/i)) {
let checkAd = $('.ima-ad-container');
player.on('touchend', () => {
if (checkAd.css('display') != 'none') {
console.log('Ad is playing.');
// do nothing
} else if (checkAd.css('display') == 'none') {
console.log('Ad is NOT playing.');
if (player.paused()) {
player.play();
} else {
player.pause();
}
}
});
$('.vjs-icon-placeholder').on('touchend', () => {
if (checkAd.css('display') != 'none') {
console.log('Ad is playing.');
// do nothing
} else if (checkAd.css('display') == 'none') {
console.log('Ad is NOT playing.');
if (player.paused()) {
player.play();
} else {
player.pause();
}
}
});
}

I have similar code to this and im wondering if there is way to make it short

I am wondering how i can make them short in my js file. i have so many code similar to this. I have repeated this if function again and again also have to repeat else function as well.The only thing is changed is Mission() Doclick() and Yesdo(). If there is way to make it short let me know thanks.
function Buy() {
if (uida == '234' || uidb == '4563') {
Mission();
} else {
stop();
};
};
function Start() {
if (uida == '234' || uidb == '4563') {
Doclick();
} else {
stop();
};
};
function ReBuy() {
if (uida == '234' || uidb == '4563') {
Yesdo();
} else {
stop();
};
};
Use function pointers!
function Uida(fn) {
if (uida == '234' || uidb == '4563') {
fn();
} else {
stop();
};
}
function Buy() {
Uida(Mission);
};
function Start() {
Uida(Doclick);
};
function ReBuy() {
Uida(Yesdo);
}
Of course, you'll want to rename the Uida function to something more descriptive :)
You could look to make them all call one similar function and pass a uida paremeter, something like this:
// You could change the following 3 functions to have ternary statements
// eg: if ( uidaCheck() ) ? Function() : stop();
//
function Buy() {
if ( uidaCheck() ) {
Mission();
} else {
stop();
}
}
function Start() {
if ( uidaCheck() ) {
Doclick();
} else {
stop();
}
}
function ReBuy() {
if ( uidaCheck() ) {
Yesdo();
} else {
stop();
}
}
function uidaCheck() {
// uida assumed to be globally accessible var
//
if ( ( uida == '234' ) || ( uida == '4563' ) ) {
return true;
} else {
return false;
}
}
That's the theory anyway, gimme a sec and I'll see if I can tidy it up a bit. (ternary)
Here's a quick jsfiddle.

Categories

Resources