Alertify confirm does not work with Ember js - javascript

I'm attempting to make a popup box which confirms if you want to delete a document. If I try:
if(alertify.confirm("Delete this?')) {
this.store.findRecord('document', docId, {backgroundReload: false}).then((doc) => {
doc.destroyRecord();
alertify.success('Document successfully deleted!');
}
it does not wait for confirmation before running the delete code, because alertify.confirm is non-blocking, as I understand. If I try:
deleteFile(docId) {
alertify.confirm("Are you sure you want to delete this document?", function (e) {
if (e) {
this.store.findRecord('document', docId, {backgroundReload: false}).then((doc) => {
doc.destroyRecord();
alertify.success('Document successfully deleted!');
});
} else {
alertify.error('Something went wrong!');
}
});
}
it does ask for confirmation, but the delete code doesn't work, as the store is coming up as undefined, so findRecord doesn't work. I've tried injecting the store as a service, but that does not work either. Is there a way to get this confirmation box working?

You use this in a function, thus referring to the this-context of that function. You could either use fat arrow functions or assign the outer this to a variable. The former would look like this:
deleteFile(docId) {
alertify.confirm("Are you sure you want to delete this document?", (e) => {
if (e) {
this.store.findRecord('document', docId, {backgroundReload: false}).then((doc) => {
doc.destroyRecord();
alertify.success('Document successfully deleted!');
});
} else {
alertify.error('Something went wrong!');
}
});
}

Related

Meteor restarts client after Meteor.call()

I'm using: meteor-base#1.4.0.
I want to redirect the user to a different page but after the insert the client it's refreshed. This means that i'm filling up a form, I store the data, I do the navigation and then with the client refresh I'm back to the form page.
// Methods.js
import { Meteor } from "meteor/meteor";
import { Players } from "../imports/api/players";
Meteor.methods({
insertPlayer(player) {
Players.insert(player);
}
})
I'm calling the method like this:
// New-player.jsx
Meteor.call("insertPlayer", player, (error) => {
if(error) {
alert("Oups something went wrong: " + error.reason);
} else {
this.props.history.push("/");
}
})
And i'm storing the values as:
// Players.js
Players.allow({
insert() { return false; },
update() { return false; },
remove() { return false; }
});
Players.deny({
insert() { return true; },
update() { return true; },
remove() { return true; }
})
Any idea what it might cause this behavior?
I'm I missing any config?
The project can be found here: https://github.com/roedit/soccer-app
I assume you are using a form submit event? Make sure before you call the Meteor Method insertPlayer you are using event.preventDefault(). If you do not event.preventDefault(), the page will refresh.

Promise.all then callback executed only one time

I have this code part, loading 3 AJAX requests and generate charts:
class IncidentStats {
constructor($statsForm) {
this.$statsForm = $statsForm;
this.charts = [];
this.$statsForm.on('submit', event => {
event.preventDefault();
this.renderCharts();
});
}
prepareFormData(key) {
const formData = this.$statsForm.serializeArray();
formData.push({
name: 'key',
value: key,
});
return formData;
}
renderCharts() {
Promise.all([
this.renderGeneralStats(),
this.renderServiceRepartitionStats(),
this.renderServerRepartitionStats(),
]).then(() => console.log('TEST'));
}
// The two other methods does nearly the same thing.
renderServiceRepartitionStats() {
return new Promise(resolve => {
$.post(this.$statsForm.attr('action'), this.prepareFormData('serviceRepartition'), data => {
this.charts['incident-service-repartition-stats'] = this.createTop10Chart(
$('#incident-service-repartition-stats'),
'Alertes Nagios',
data
);
resolve();
}, 'json');
});
}
}
I use promise in order to do some stuff at the very end of the 3 charts loading, but want to keep the loading sync.
The console.log('TEST') on the then callback works at the first loading.
On second form submit, the charts are indeed reloaded but the then callback is never called.
I'm sure I'm missing something, but what? :-)
Thanks
So I finally found the solution. Just do not create a new Promise when you are using jQuery ajax call. Just returns the call works because it's also a promise:
renderServiceRepartitionStats() {
return $.post(this.$statsForm.attr('action'), this.prepareFormData('serviceRepartition'), data => {
this.charts['incident-service-repartition-stats'] = this.createTop10Chart(
$('#incident-service-repartition-stats'),
'Alertes Nagios',
data
);
}, 'json');
}
I understand using new Promise is overkill here, but I don't know why this was causing my issue... Maybe someone can add some details here.

Disable and re-enable button on single action

I need to disable and re-enable a button during the async call. I am only able to disable it. If I add code to re-enable it is ignored. I acknowledge I may not be asking the right question.
I have a function with a button "Action":
<button className={`doFoo${buttonClasses[type]} ${type}`} onClick={onClick} disabled={isButtonDisabled}>
That is called by a React class "Actions":
<Action type="like" onClick={onLike} isButtonDisabled={isButtonDisabled} />
That is called by another React class "List":
<Actions onLike={this.handleLike} onDislike={this.handleDislike} isButtonDisabled={isButtonDisabled}/>
Also in that class is are the following functions:
...
thumbsUp() {
const {
...
} = this.props;
const {
...
} = this.state;
this.setState({ wasLiked: true, viewProfile: false }, () => {
setTimeout(doThumbsUp, ACTION_CONFIRMATION_ANIMATION_TIMEOUT);
});
function doThumbsUp() {
thumbsUp({
index: activeIndex,
id: profiles[activeIndex].id
});
}
},
handleLike() {
const { showThumbsUpConfirmation } = this.props;
if (showThumbsUpConfirmation) {
this.showThumbsUpConfirmationModal();
} else {
this.thumbsUp();
}
},
...
Here's what the source looks like:
export function thumbsUp({ id, ... }) {
return api.post(`${API.ENDPOINTS.FOO}/${id}/thumbs_up`, {
...
});
}
I can place this.setState(isButtonDisabled: true) at various places in this code and that value makes it to the view and disables the button. However I cannot figure out how to re-enable the button after the work has been done.
If I'm understanding you correctly you want the button to be disabled during async and after async be enabled? If that is the case, wherever you are calling the function that makes the api call, you just need to chain a .then(() => this.setState(isButtonDisabled: false) and that will update the state as soon as response has been received from api call. also if you aren't using es6 just make sure to set this to a variable above the api call to ensure its scoped properly for setState

Issues retrieving fbsdk Access Token and User ID

I am trying to retrieve the Access Token and User ID of the logged in user in my React Native App. For some reason when I tried to update the fbsdkcore package, it did not exist anymore. So, I tried to resolve it within the general fbsdk package.
I am calling the js file (of which I think retrieves the accesstoken) in the package as:
const AccessToken = require('react-native-fbsdk/js/FBAccessToken');
And subsequently in my code I try to log it so that I can see if it works, simply by:
console.log(AccessToken.getCurrentAccessToken());
console.log(AccessToken.getUserId);
But the log only returns:
2016-05-05 10:22:28.276 [info][tid:com.facebook.React.JavaScript] { _45: 0, _81: 0, _65: null, _54: null }
2016-05-05 10:22:28.277 [info][tid:com.facebook.React.JavaScript] undefined
Which does not seem to be the droids that im looking for.
I inspected the code for the js file in the fbsdk package and the getCurrentAccessToken code looks like this:
/**
* Getter for the access token that is current for the application.
*/
static getCurrentAccessToken(): Promise<?FBAccessToken> {
return new Promise((resolve, reject) => {
AccessToken.getCurrentAccessToken((tokenMap) => {
if (tokenMap) {
resolve(new FBAccessToken(tokenMap));
} else {
resolve(null);
}
});
});
}
Which of course seems reasonable. But since I get this really weird result when I try to call it, I get worried over that I have done something wrong in the bigger picture. I even modified the resolve(null) part of the code so that I could make sure of what happend. But it still returned the same weird "token".
The log also returns this error when logging in:
2016-05-05 10:22:07.630 AppName[15097:415865] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
But I think that is only because I don't have the facebook app on my xcode simulator.
Can anybody throw me a good guess on what I have done wrong??
GetCurrentAccestoken returns a promise.
Maybe you can try:
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken.toString())
}
)
Try this. It worked for me
AccessToken.getCurrentAccessToken().then(
(data) => {
console.log(data.accessToken)
console.log(data.userID);
});
LoginManager.logInWithReadPermissions(['public_profile']).then(
function (result) {
if (result.isCancelled) {
alert('Login cancelled');
} else {
// alert('Login success with permissions: ' +
// result.grantedPermissions.toString());
AccessToken.getCurrentAccessToken().then(
(data) => {
doLoginViaFb(data.userID, data.accessToken);
}
);
alert(result);
console.log(result.toString());
console.log(JSON.stringify(result));
}
},
function (error) {
alert('Login fail with error: ' + error);
}
);

Meteor: Security in Templates and Iron Router

I'm enjoying working with Meteor and trying out new things, but I often try to keep security in mind. So while I'm building out a prototype app, I'm trying to find the best practices for keeping the app secure. One thing I keep coming across is restricting a user based on either a roll, or whether or not they're logged in. Here are two examples of issues I'm having.
// First example, trying to only fire an event if the user is an admin
// This is using the alaning:roles package
Template.homeIndex.events({
"click .someclass": function(event) {
if (Roles.userIsInRole(Meteor.user(), 'admin', 'admin-group') {
// Do something only if an admin in admin-group
}
});
My problem with the above is I can override this by typing:
Roles.userIsInRole = function() { return true; } in this console. Ouch.
The second example is using Iron Router. Here I want to allow a user to the "/chat" route only if they're logged in.
Router.route("/chat", {
name: 'chatHome',
onBeforeAction: function() {
// Not secure! Meteor.user = function() { return true; } in the console.
if (!Meteor.user()) {
return this.redirect('homeIndex');
} else {
this.next();
}
},
waitOn: function () {
if (!!Meteor.user()) {
return Meteor.subscribe("messages");
}
},
data: function () {
return {
chatActive: true
}
}
});
Again I run into the same problem. Meteor.user = function() { return true; } in this console blows this pattern up. The only way around this I have found thus far is using a Meteor.method call, which seems improper, as they are stubs that require callbacks.
What is the proper way to address this issue?
Edit:
Using a Meteor.call callback doesn't work for me since it's calling for a response asynchronously. It's moving out of the hook before it can handle the response.
onBeforeAction: function() {
var self = this;
Meteor.call('someBooleanFunc', function(err, res) {
if (!res) {
return self.redirect('homeIndex');
} else {
self.next();
}
})
},
I guess you should try adding a check in the publish method in server.
Something like this:
Meteor.publish('messages') {
if (Roles.userIsInRole(this.userId, 'admin', 'admin-group')) {
return Meteor.messages.find();
}
else {
// user not authorized. do not publish messages
this.stop();
return;
}
});
You may do a similar check in your call methods in server.

Categories

Resources