Scope of 'this' on onTap and on popUp in ionic is 'undefined' - javascript

I want to show a popUp in ionic, which does not allow the user to exit when he hasn't entered some input. Right now I'm using this here:
public showOwnIdentifierPrompt() {
// Prompt popup code
var promptPopup = this.$ionicPopup.prompt({
title: this.floor_name,
template: `<input ng-model="$ctrl.customFloorName"></input>`,
scope: this.$scope,
buttons: [
{
text: this.cancel,
type: 'button-clear button-balanced',
onTap: function(e) {
// Cancel creation
return false;
}
},
{
text: this.save,
type: 'button-clear button-balanced',
onTap: () => {
// Create new floor
return true;
}
}
]
});
promptPopup.then((res) => {
if (res) {
this.addNewFloor(this.customFloorName);
}
})
}
In the save onTap() event handler, I would like to access this.customFloorName from my class, to decide whether the user entered input. But it is always undefined. What can I do?

You can get value on Save with below code :
var value = this.scope.$ctrl.customFloorName;

Related

How to set back the old value of radio button when user select No from confirm Box?

I have a problem that I have to trigger the User confirm box when the user makes the change on the radio button.
I successfully trigger the Confirm Box but challenging for me to set the old value in the radio group.
Anyone has any idea to do that.
I tried solution mention on google but no luck.
Ext.define('CustomRadioField', {
override: 'RadioField',
setListeners: function(config) {
var me = this;
config.listeners = {
change: {
fn: function(control, newValue, oldValue, eOpts) {
var me = this;
me.fieldChanged();
Ext.Msg.confirm(MyFunction.T('Confirm'), "Are you sure want to delete?", function(btn) {
if (btn == 'no') {
//Added my logic to reset back
control.suspendEvent('change');
control.setValue(oldValue);
control.resumeEvent('change');
//End
//Added to refresh page not to reload but this location.reload post to my server insted to refresh.
location.reload();
}
if (btn == 'yes') {
}
});
}
},
scope: me
},
focus: {
fn: me.storeFocusField,
scope: me
},
afterrender: {
fn: function(f, e) {
me.setFieldFocus;
},
scope: me
},
boxready: {
fn: me.setUpChangeEvent,
scope: me
},
specialkey: {
fn: function(f, e) {
var me = this;
switch (e.getKey()) {
case e.TAB:
break;
}
},
scope: me
}
};
},
});
Thanks in advance
can you attach the code?
You can use field.reset() function to reset field value, where field is radio button field or you can use form.reset() method to reset all fields in form to state before user change.

Confirm DatePicker time change

So I have a DatePicker that I can change a certain field with, but I want it to update the HTML only when the user confirms the change.
However, currently, when I use the (ionChange) event in my ion-datetime element, it updates the UI automatically before my confirmation alert pops up.
How can I make it so that the value in my date picker will only change when the user presses confirm?
updateStartTime(startTime) {
let alert = this.alertControl.create({
title: 'Change start time',
message: 'Are you sure you want to update the start time for this event?',
buttons: [{
text: 'Cancel',
handler: () => {
console.log('cancel');
}
}, {
text: 'Confirm',
handler: () => {
console.log(startTime);
}
}]
});
alert.present();
}
<ion-item detail-push>
<ion-label><b>Start: </b></ion-label>
<ion-datetime displayFormat="hh:mm A"
[(ngModel)]="item.EventStart"
(ionChange)="updateStartTime(item.EventStart)"></ion-datetime>
</ion-item>
You could just do a trick by keeping the old value of the EventStart. I added two code samples. First one will update the HTML but it will only keep the updated value if click on confirmation, otherwise it will set DatePicker to old value back. Second one will work as you expected but I don't know your value of item.EventStart is look like. I just guess it would something similar to this pattern '00:00'. Sample codes will worth you than explanation in words :).
First one
public oldEventStart = this.item.EventStart;
updateStartTime(startTime) {
let alert = this.alertControl.create({
title: 'Change start time',
message: 'Are you sure you want to update the start time for this event?',
buttons: [
{
text: 'Cancel',
handler: () => {
this.item.EventStart = this.oldEventStart;
console.log('cancel');
}
},
{
text: 'Confirm',
handler: () => {
this.item.EventStart = startTime;
this.oldEventStart = startTime;
console.log(startTime);
}
}
]
});
alert.present();
alert.onDidDismiss(() => { this.item.EventStart = this.oldEventStart; });
}
Second one
public oldEventStart = this.item.EventStart;
updateStartTime(startTime) {
this.item.EventStart = new Date('2000-01-01T'+this.oldEventStart+':00.00').toISOString();
let alert = this.alertControl.create({
title: 'Change start time',
message: 'Are you sure you want to update the start time for this event?',
buttons: [
{
text: 'Cancel',
handler: () => {
this.item.EventStart = this.oldEventStart;
console.log('cancel');
}
},
{
text: 'Confirm',
handler: () => {
this.item.EventStart = startTime;
this.oldEventStart = startTime;
console.log(startTime);
}
}
]
});
alert.present();
alert.onDidDismiss(() => { this.item.EventStart = this.oldEventStart; });
}
Hope this will help to solve your problem. Cheers!.
When I use a bootstrap dialog I would use a prevent default. Try to change the following: updateStartTime(startTime) to updateStartTime(startTime,e) and then on your first line in that function add e.preventDefault(); See if that helps. You should then be able to do whatever you like in your cancel and confirm handlers.
Just return false in your updateStartTime function, so that the default datepicker handler that is bound to the change event does not get called. Like this:
updateStartTime(startTime) {
let alert = this.alertControl.create({
title: 'Change start time',
message: 'Are you sure you want to update the start time for this event?',
buttons: [{
text: 'Cancel',
handler: () => {
console.log('cancel');
}
}, {
text: 'Confirm',
handler: () => {
console.log(startTime);
}
}]
});
alert.present();
/** prevent default datepicker behavior **/
return false;
}

Javascript - prevent navigation during file upload

I have a vue component for video upload, where I am warning a user when he tries to navigate away during the video upload that he will lose the file if he does so, like this:
ready() {
window.onbeforeunload = () => {
if (this.uploading && !this.uploadingComplete && !this.failed) {
this.confirm('Are you sure you want to navigate away? Your video won't be uploaded if you do so!');
}
}
}
I am using sweetalert to alert the user about it. But how can I then make it stay on the same page, and prevent the navigation away before he confirms that he wants to navigate away?
This is the whole component:
<script>
function initialState (){
return {
uid: null,
uploading: false,
uploadingComplete: false,
failed: false,
title: null,
link: null,
description: null,
visibility: 'private',
saveStatus: null,
fileProgress: 0
}
}
export default {
data: function (){
return initialState();
},
methods: {
fileInputChange() {
this.uploading = true;
this.failed = false;
this.file = document.getElementById('video').files[0];
this.store().then(() => {
var form = new FormData();
form.append('video', this.file);
form.append('uid', this.uid);
this.$http.post('/upload', form, {
progress: (e) => {
if (e.lengthComputable) {
this.updateProgress(e)
}
}
}).then(() => {
this.uploadingComplete = true
}, () => {
this.failed = true
});
}, () => {
this.failed = true
})
},
store() {
return this.$http.post('/videos', {
title: this.title,
description: this.description,
visibility: this.visibility,
extension: this.file.name.split('.').pop()
}).then((response) => {
this.uid = response.json().data.uid;
});
},
update() {
this.saveStatus = 'Saving changes.';
return this.$http.put('/videos/' + this.uid, {
link: this.link,
title: this.title,
description: this.description,
visibility: this.visibility
}).then((response) => {
this.saveStatus = 'Changes saved.';
setTimeout(() => {
this.saveStatus = null
}, 3000)
}, () => {
this.saveStatus = 'Failed to save changes.';
});
},
updateProgress(e) {
e.percent = (e.loaded / e.total) * 100;
this.fileProgress = e.percent;
},
confirm(message) {
swal({
title: message,
text: null,
type: "warning",
showCancelButton: true,
cancelButtonText: "Cancel",
cancelButtonColor: '#FFF',
confirmButtonColor: "#2E112D",
confirmButtonText: "Yes, delete"
}).then(function(){
this.$data = initialState();
}.bind(this), function(dismiss) {
// dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
}
},
ready() {
window.onbeforeunload = () => {
if (this.uploading && !this.uploadingComplete && !this.failed) {
this.confirm('Are you sure you want to navigate away? Your video won't be uploaded if you do so!');
}
}
}
}
</script>
Mozilla documentation suggests
window.onbeforeunload = function(e) {
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
};
and also states that:
Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.
Source contains many other details regarding reasons and what to expect from modern browsers.
This question seems to be a duplicate of yours.
This answer suggests that to avoid weird browser behaviour you should set handler only when it's to prevent something (that is while navigating away should trigger a confirmation dialog)
But how can I then make it stay on the same page, and prevent the navigation away before he confirms that he wants to navigate away?
Add return false; to stop the event.
if (this.uploading && !this.uploadingComplete && !this.failed) {
this.confirm("Are you sure you want to navigate away? Your video won't be uploaded if you do so!");
return false; // <==== add this
}
return false; does 3 separate things when you call it :
event.preventDefault(); – It stops the browsers default behaviour.
event.stopPropagation(); – It prevents the event from propagating (or “bubbling up”) the DOM.
Stops callback execution and returns immediately when called.

handling Multiple buttons in $ionicPopup prompt

The documentation says:
Show a simple prompt popup, which has an input, OK button, and Cancel
button. Resolves the promise with the value of the input if the user
presses OK, and with undefined if the user presses Cancel.
I was doing:
$ionicPopup.prompt({
//options
}).then(function (userinput) {
//get userinput and send to server
});
I need to add a third button, but can't get the text of the input, how can I resolve the promise on the onTap event of the button to get the input?
$ionicPopup.prompt({
title: '¿Are you sure?',
inputType: 'text',
buttons: [
{ text: 'Cancel'
//close popup and do nothing
},
{
text: 'NO',
type: 'button-assertive',
onTap: function(e) {
//send to server response NO
}
},
{
text: 'YES',
type: 'button-energized',
onTap: function(e) {
//get user input and send to server
}
}]
See this demo i made with your code: http://play.ionic.io/app/ac79490c8914
prompt() is not meant to add more than two buttons,show() is used to make complex pop ups, Please see show() method in same documentation. As written in documentation, i am quoting:
Show a complex popup. This is the master show function
for all popups.
A complex popup has a buttons array, with each button having a text
and type field, in addition to an onTap function.
Your code will be like:
$scope.showPop = function(){
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="data.myData">',
title: '¿Are you sure?',
scope: $scope,
buttons: [
{ text: 'Cancel'
//close popup and do nothing
},
{
text: 'NO',
type: 'button-assertive',
onTap: function(e) {
return null;
}
},
{
text: 'YES',
type: 'button-energized',
onTap: function(e) {
return $scope.data.myData;
}
}]
});
myPopup.then(function(userinput) {
if(userinput){
console.log('returned data'+ userinput)
}
});
}
Simple thing about above code is that you have bind input with $scope (<input type="text" ng-model="data.myData">) so you can access it in any manner.

Dialog cancel button needs to stop browser event

I am trying to display a dialog/confirm when a user browses away from a page/component.
I have the following dialog component which currently fires using a listener:
emptyBasket: function () {
basketChannel.publish({
channel: "basket",
topic: "emptyBasket",
data: {
}
});
},
OnClick which fires publish:
onTabLinkClick: function(e) {
var url = window.location.href;
var currentRoute = url.substr(url.length - 6)
if(this.state.BasketTotal > 0 && currentRoute != 'basket' ){
basketChannel.publish({
channel: "basket",
topic: "openDialog",
data: {
dialogTitle: 'Warning',
dialogContent: 'You have contacts in your basket, are you sure you want to leave?'
}
});
}
}
The listener in my dialog component then changes the state and displays the dialog:
_listenerForDialog: function(data) {
this.setState({
title: data.dialogTitle,
content: data.dialogContent,
visible:true
});
},
This works, but I would like to add an ok and cancel button, if the cancel button is clicked I would like stop the event.
How could I attach my component to e.preventDefault()?
Can I make this work like the native browser confirm()?
var confirmDialog = confirm("You have contacts in your basket, are you sure you want to leave?");
if(confirmDialog == false ){
e.preventDefault();
} else{
this.emptyBasket();
}
I am using the npm package https://www.npmjs.com/package/rc-dialog
UPDATED
onClose in current component:
onClose(){
this.setState({
visible:false
});
basketChannel.publish({
channel: "basket",
topic: "emptyBasket",
data: {
}
});
},
Thanks in advance

Categories

Resources