Coder1000 Coder1000 - 1 month ago 9
Node.js Question

How to load a server variable only after a specific event?

I need the two server variables to be loaded only after the var change in the db.

Right now, they load immediately when the page is loaded and therefore keep the value they had before the event (

upvotesRef.transaction
).

$('.HP').text("<%= post.upvotes - post.downvotes %> HP");





CODE:

$('.UpvoteButton').click(function () {


var $this = $(this);
if ($this.hasClass("on")) {
$this.removeClass("on");
upvotesRef.transaction(function (upvotes) {
if (!upvotes) {
upvotes = 0;
}
upvotes = upvotes - 1;
return upvotes;
});
userRef.remove();
$('.HP').text("<%= post.upvotes - post.downvotes %> HP");





EDIT:

I ended up creating local variables to solve my problem. Thank you for your answers !

var upvotesLocal = <%= post.upvotes %>;
var downvotesLocal = <%= post.downvotes %>;

$('.UpvoteButton').click(function () {


var $this = $(this);
if ($this.hasClass("on")) {
$this.removeClass("on");
upvotesRef.transaction(function (upvotes) {
if (!upvotes) {
upvotes = 0;
}
upvotes = upvotes - 1;
return upvotes;
});
upvotesLocal = upvotesLocal -1
userRef.remove();
$('.HP').text((upvotesLocal - downvotesLocal) + " HP")

Answer

you should get and update the variables AFTER the transaction right?
That means it should happen in your callback.
I assume you are using the firebase transaction method.
then your callback should be as second parameter:

$('.UpvoteButton').click(function () {


        var $this = $(this);
        if ($this.hasClass("on")) {
            $this.removeClass("on");
            upvotesRef.transaction(function (upvotes) {  
               if (!upvotes) { 
                  upvotes = 0; 
               } 
                 upvotes = upvotes - 1; 
                 return upvotes; 
            }, updateVotes); //<-- here the callback function added
            userRef.remove();

function updateVotes(error, isCommitted, upvotes) {
   //here you got already your new upvotes
   //but you should request the downvotes,
   //here you need the ajax request, see e.g. Dez's answer or comments
}