Meteor: How execute JS after insert in collection - javascript

I am working on a chat app using Meteor.
After sending the message, it should show the message and scroll to the bottom. But how can I execute a JS to scroll down, AFTER the insert?
Template.addMessage.events({
'submit form': function(e) {
Messages.insert({
user: 'username',
message: 'my message',
date: new Date()
});
window.scrollTo(0, document.body.scrollHeight);
}
});
Apparently it is scrolling down before the view refreshes with the new record. How can it be executed after the view updates?

Use Collection.insert's callback
Template.addMessage.events({
'submit form': function(e) {
Messages.insert({
user: 'username',
message: 'my message',
date: new Date()
}, function(){
// add your code here
window.scrollTo(0, document.body.scrollHeight);
});
}
});

Related

Dynamically change a value of instance already created in JavaScript

I'm using "Braintree - Dropin" here. Instance is created when page load and I have a dropdown to select "pay amount" after. I want to update value of instance (already created) when dropdown is changed.
var form = document.querySelector('#payment-form');
var client_token = "{{ Braintree\ClientToken::generate()}}";
var amount = document.getElementById("amount");
var amount_val = amount.options[amount.selectedIndex].value;
braintree.dropin.create({
authorization: client_token,
selector: '#bt-dropin',
applePay: {
displayName: 'My Store',
paymentRequest: {
total: {
label: 'My Store',
amount: amount_val
}
}
}
}, function (createErr, instance) {
if (createErr) {
console.log('Create Error', createErr);
return;
}
amount.addEventListener("change", function() {
console.log(amount.value);
// Where i'm trying to change amount
instance.updateConfiguration('applePay', 'paymentRequest', {
total: {
label: 'My Store',
amount: amount.value
}
});
});
form.addEventListener('submit', function (event) {
event.preventDefault();
instance.requestPaymentMethod(function (err, payload) {
if (err) {
console.log('Request Payment Method Error', err);
return;
}
// Add the nonce to the form and submit
document.querySelector('#nonce').value = payload.nonce;
form.submit();
});
});
});
According to "Dropin" documentation this should work. but it doesn't.
https://braintree.github.io/braintree-web-drop-in/docs/current/Dropin.html#updateConfiguration
I couldn't find a possible way to change instance after it is created. But I solved the problem by splitting process in to two parts. I made two steps to do the payment. In first page user will select amount from dropdown then click next button which submit selected amount into payment page. then on payment page this instance is created with amount already post from previous page. Hope this will help someone with a similar issue.

Execute JS function after successful stripe payment

I've decided to use the custom button code supplied by Stripe for accepting payment on a single product I sell. It looks like this:
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Hire Bike (1 Day)</button>
<script>
var handler = StripeCheckout.configure({
key: 'MY_KEY',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Bike Company',
description: '1 Day Bike Hire',
currency: 'usd',
amount: 25000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
While it does work (when I use my actual public API key of course), what I can't find a solution for is a way to execute some of my own JS when the payment is successful.
I can't find an answer in the documentation, so looking for suggestions from the SO community.
You can run code in the token callback:
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Hire Bike (1 Day)</button>
<script>
var handler = StripeCheckout.configure({
key: 'MY_KEY',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// DO STUFF HERE
alert("Wahoo! You paid!")
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Bike Company',
description: '1 Day Bike Hire',
currency: 'usd',
amount: 25000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>

Form Validation jQuery plugin success.form.fv event not working

I am trying to build a dynamic popup that allows the user to edit data in a datatable without redirecting the page. I am using NodeJS with jQuery 'modal' library for the popup and 'formvalidation' library to validate and submit the data. (Note: This is not the same library as jquery validate).
Here's a demo of exactly what I am attempting to accomplish.
http://formvalidation.io/examples/loading-saving-data-modal/
I got most of the code working, I was able to display the modal window, passing in data and the validation works properly, too. The problem is that the success.form.fv event is not being triggered, the dialog just closes.
script.
$(document).ready(function () {
$('#editFilepathForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
id: {
validators: {
notEmpty: {
message: 'ID is required'
}
}
},
edited_filepath: {
validators: {
notEmpty: {
message: 'Edited Filepath is required'
},
regexp: {
regexp: /^[a-zA-Z\s]+$/,
message: 'The full name can only consist of alphabetical characters'
}
}
},
edited_filename: {
validators: {
notEmpty: {
message: 'Edited Filename is required'
},
regexp: {
regexp: /^[a-zA-Z\s]+$/,
message: 'The full name can only consist of alphabetical characters'
}
}
}
}
})
//THIS EVENT IS NOT TRIGGERING AT ALL. ALERT MESSAGE DOES NOT APPEAR. THE BOX JUST CLOSES AFTER SUCCESSFUL VALIDATION.
.on('success.form.fv', function (e) {
alert('success');
// Save the form data via an Ajax request
e.preventDefault();
var $form = $(e.target),
id = $form.find('[name="id"]').val();
// Hide the dialog
$form.parents('.bootbox').modal('hide');
// You can inform the user that the data is updated successfully
// by highlighting the row or showing a message box
bootbox.alert('The user profile is updated');
//});
});
$('.editButton').on('click', function () {
var id = $(this).attr('data-id');
var requested_filepath = $(this).attr('data-requested-filepath');
var requested_filename = $(this).attr('data-requested-filename');
/*Set original requested values to display in modal form window*/
$('#editFilepathForm')
.find('[name="id"]').html(id).end()
.find('[name="requested_filepath"]').html(requested_filepath).end()
.find('[name="requested_filename"]').html(requested_filename).end()
.find('[name="edited_filepath"]').val(requested_filepath).end()
.find('[name="edited_filename"]').val(requested_filename).end()
// Show the dialog
bootbox
.dialog({
title: 'Edit Requested Filepath',
message: $('#editFilepathForm'),
show: false // We will show it manually later
})
.on('shown.bs.modal', function () {
$('#editFilepathForm')
.show() // Show the login form
.formValidation('resetForm'); // Reset form
})
.on('hide.bs.modal', function (e) {
// Bootbox will remove the modal (including the body which contains the login form)
// after hiding the modal
// Therefor, we need to backup the form
$('#editFilepathForm').hide().appendTo('body');
})
.modal('show');
//});
});
});
I was able to resolve the issue by adding the 'excluded' property as explained in the documentation.
http://formvalidation.io/examples/modal/

i'm trying to keep my webview hidden till the URL is finished loading

I have an ionic app that loads an external site into a webview, I see a blank page each time the webview is loaded before the url is finished loading. I would like the webview to show only after the url is done loading. I also have an eventlistener for loadstart, that is meant to close the window when that url is hit and return to the ionic app homescreen, this works on my emulator but on my real device it just shows a blank page with symbols.
$scope.login = function()
{
//check if network is connected before sending initial request
if(monitor.isOffline())
{
var alertPopup = $ionicPopup.alert({
title: 'Network Error!',
template: "Your Network is Offline, please connect and try again"
});
}
//show spinner while loading page
$scope.show = function() {
$ionicLoading.show({
template: '<p>Loading...</p><ion-spinner></ion-spinner>'
});
};
//hide spinner
$scope.hide = function(){
$ionicLoading.hide();
};
//send initial request
AuthService.login($scope.user).then(
function(home)
{
$scope.show($ionicLoading);
if(monitor.isOnline())
{
$scope.show($ionicLoading);
var ref = window.open(home, '_blank', 'location=no,toolbar=no');
ref.addEventListener('loadstart', function (event)
{
if(event.url == "http://mobile.map.education/logout" )
{
ref.close();
}
});
ref.addEventListener('loaderror', function (event)
{
var alertPopup = $ionicPopup.alert({
title: 'Network Error',
template: "Oops,Error with your network"
});
ref.close();
});
$scope.hide($ionicLoading);
//watch network state
monitor.startWatching();
}
if(monitor.isOffline())
{
var alertPopup = $ionicPopup.alert({
title: 'Network Error',
template: "Oops,Error with your network"
})
}
},
function (errMsg)
{
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: errMsg
});
})
.catch(function()
{
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Server not responding'
})
.finally(function ($ionicLoading)
{
$scope.hide($ionicLoading);
});
});
};
I think this working only with InAppBrowserPlugin but you can open the window with hidden=yes
var ref = window.open(home, '_blank', 'location=no,toolbar=no,hidden=yes');
then:
ref.addEventListener('loadstop', function(){
ref.show();
});
check the doc here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/

$ionicPopup: e.preventDefault() gets ignored

I'm using the following code for some validation stuff using both $ionicPopup and Firebase:
onTap: function(e) {
firebase.auth().applyActionCode($scope.data.emailcnfrm)
.then(function() {
return $scope.data.emailcnfrm;
},
function(error) {
alert("wrong code");
e.preventDefault();
});
}
But In the case of error, and after I get the "wrong code" alert, the popup gets closed, as e.preventDefault(); has been ignored.
So what's exactly wrong in my code? and how can I fix this problem?
Your call to firebase.auth().applyActionCode is asynchronous, and e.preventDefault will be called asynchronously in the error callback. This happens after the user has already invoked onTap, thus e.preventDefault won't have any effect.
Edit (a proposed fix)
To fix it, you could separate the async logic from the onTap method:
var myPopup = $ionicPopup.show({
onTap: function(e) {
// always keep the popup open, because we'll decide when to close it later
e.preventDefault();
}
});
myPopup.then(function(res) {
firebase.auth().applyActionCode($scope.data.emailcnfrm)
.then(function() {
// if successful, imperatively close the popup
myPopup.close();
}, function(err) {
// log the error, or something
});
});
Finally I solved the problem by using my own trick:
-outside Async:
$scope.myPopup = $ionicPopup.show({
scope: $scope, buttons: [
{ text: 'Cancel' },
{
text: '<b>Done</b>',
type: 'button-positive',
onTap: function(e)
{
// always keep the popup open, because we'll decide when to close it later
e.preventDefault();
$AsyncCallback();
}
}
]
});
$scope.myPopup.then(function(){},
function(error)
{
$ionicPopup.alert({
title: 'Internal error!',
template: error
});
});
-inside async:
$scope.myPopup.close();

Categories