remembering a javascript var each call to function - javascript

I've got a nice little shopping basket where if the user deletes an item, the slideup jquery function is called and is disappears.
In the back ground, I'm removing it from the db with a call to a code igniter controller.
function delete_booking(id_booking, amount) {
if (user_total == null || user_total == '') {
var user_total = parseFloat(0);
}
$.ajax({
type: "POST",
data: '',
url: "/"+id_booking,
});
$("#booking_id_"+id_booking).slideUp();
var user_total = (parseFloat() - parseFloat() - parseFloat(user_total));
alert(user_total);
alert(parseFloat(user_total));
$('#booking_total').html(user_total);
}
What I can't fathom, is when I update the user total: $('#booking_total')
I need somehow to have the function remember the NEW total...
I've googled 'remembering JavaScript var' and similar, but I can't find exactly what I need...
My only other option is to do another call to the db with ajax to get the new total, but there MUST be a JS way to do this?

If you are not navigating to a different page, you can store the value in a variable that is outside the function (whether just on the page in the global namespace or the within the module in which the function resides).
var total;
function delete_booking(...)
{
...
total = user_total;
}

as you have said
I need somehow to have the function
remember the NEW total
a function cant remember a value, while a variable can, to solve your problem do one the below
1
var finalTotal;
function delete_booking(...)
{
//your more codes
$('#booking_total').html(user_total);
finalTotal = user_total;
}
now variable finalTotal hold the value
2
whenever you feel that you need to access the total read this way
var total=parseint($('#booking_total').html(),10) || 0;
But think method 1 is better than method 2

Because I "hate" a global approach for this type of problem, here is a little closure which will do the job of "remembering" the value (although I'm not really sure what exactly should be saved...^^)
var delete_booking = (function() {
var booking_total = $("#booking_total"),
total_amount = parseFloat(booking_total.html()) || 1000; // what ever the value should be...
return function(id, m) {
$.ajax(/* ... */);
$("#booking_id_"+id).slideUp();
total_amount -= m;
booking_total.html(total_amount);
}
}());

Related

How can I return a value from function with multiple nested functions in Javascript?

The problem: I want to call a value from a nested method outside of its parent method. In other words, I want the output from "console.log(someObjects[i].valueChecker);" to be either "true" or "false." However, it is just returning the function itself.
What I've done so far: So I have been scouring the web/stack overflow for a solution, but either I haven't found a solution, or I just can't make sense of it. I think it has something to do with "closures," and most of the solutions to problems I've seen have been to return from the submethod, and then return the submethod from the parent method. However, every time I've tried this, I've just encountered numerous errors-- either another submethod suddenly doesn't exist, or the code runs, but the output is still a function. I wonder if having multiple methods affects the issue.
Context: I'm making a platformer game, and there are multiple types of the same enemy. I want to check for collision between the player and weapon and thusly need some values from the enemy function (I don't want to use the word "class," but I'm not sure about the appropriate terminology). I'm much more familiar with Java though, so it is frustrating me to not be able to create a separate class and just have a method to give me values back.
//assume all the other html/main stuff is already set up
var temp = {
create: c4,
update: u4
}
MyObject = function(value) {
this.value = value; //passed in value
var magicNumber = 4; //local value initialized/declared
this.valueChecker = function() {
//return boolean
return this.value == this.magicNumber;
}
this.otherValueChecker = function() {
//return boolean
return (this.value + 1) == this.magicNumber;
}
}
//just make the space bar tied to a boolean
var someKeyPress;
function c4() {
someKeyPress = game.input.keyboard.addKey(Phaser.Keyboard.A);
}
var someObjects = [];
//... later on in the program, presuming key already coded
function u4() {
//add a new MyObject to array someObjects
if (someKeyPress.isDown) {
//check with various random numbers between 3 to 5
someObjects.push(new MyObject(game.rnd.integerInRange(3, 5)));
}
//run through MyObject(s) added to someObjects, and see if any match number
for (var i = 0; i < someObjects.length; i++) {
console.log(someObjects[i].valueChecker);
}
}
/* current output
ƒ () {
//return boolean
return this.value == this.magicNumber;
}
*/
Try
console.log(someObjects[i].valueChecker())
Because I see the value checker as a function
this.valueChecker = function()

Wait for an async callback to finish before completing separate function in Javascript

Apologies if this is a repeat, but all I can find is help to let the function finish or unrelated languages, not what to do after. Anyway...
So, I have two other-wise unrelated functions. One calls the Namey API, which returns a random name in a callback, and I use that to update an element. This is my randomizePANameListeners function.
My second function takes the first name and last name from those two elements and uses them to create a random username. This is my randomizeAppNameListeners.
randomizePANameButton.addEventListener("click", function(e) {
// Check the gender of the PA
var isChecked = document.getElementById("gender56").checked;
// Use a self-invoking function to make sure the names are
// updated correctly
(function() {
if (isChecked === true) {
namey.get({ type: 'male', with_surname: 'false', frequency: 'all', callback: function(n) { document.getElementById("fName").value = n }});
} else {
namey.get({ type: 'female', with_surname: 'false', frequency: 'all', callback: function(n) { document.getElementById("fName").value = n }});
}
// Set the surname as well
namey.get({ type: 'surname', with_surname: 'false', frequency: 'all', callback: function(n) { document.getElementById("lName").value = n }});
})()
And, attached to a second button's event listener:
var fName = document.getElementById("fName").value.substring(0, 3);
var lName = document.getElementById("lName").value;
var randomDigits = (Math.random() * (100 - 10) + 10).toFixed(0);
return fName + lName + ".UAT" + randomDigits;
Now, I have one button to make everything easier by tying all of these event listeners together. My easy button does everything for me, but when it calls these two it takes the current values in the elements to make the random name and then creates a new application name, it doesn't take the new PA name.
So, using vanilla JavaScript, how do I wait for the first function to complete before finishing the second? I would prefer not to create an unneeded global variable.
In native javascript you can use callbacks in your own functions
var myFunction = function(complete) {
/* Do things here first */
complete();
}
myFunction(function(){
/* Do Something else here after the first has completed */
});
You can try doing it with promises - http://www.html5rocks.com/en/tutorials/es6/promises/
This should work :)
Yes use promises which works for exactly in your scenario and if you are using jquery, you can use deferred.
https://api.jquery.com/jquery.deferred/

efficiently creating variables when a checkbox is checked and using these variables later in the code

below is the information I need help with.
$(document).ready(function(){
$('.checkboxes :checkbox').click(function(){
if($(this).is(':checked')){
console.log(this.id + this.checked)
i want to set a variable with the samename of the id of the checked box
so if showItems was checked i would have a variable
var showItems = true;
I want this so I could see if showItems is checked which would alow me to perform the proper functions
i think i could do something like this
if($this.id = "withones"){
var withones = true;//on
}
if($this.id = "withoutOnes"){
var withoutOnes = true;//on
}
etc.
i feel like the above is a rookie way to code. lets say i have alot of checkboxes and it also looks like im repeating myself. I tried putting the ids in an array and loop through them but I got the html element in the console when i clicked on the box. I would like for someone to tell me if there is a more efficient way to set up these variables. and if so show me please.
Also I'm new to programming so thanks for your help so far. but I was also thinking about another problem. if I set up these variables here and I want to set up another function somewhere else to perform mathematical operations perse. i want that function to be able to evaluate the value of the withones and withoutOnes variables so I would like to do something like this in the function
function add(){
if(withones){ //true|| false
return 2 + 2;
}
if (withoutOnes) {
return 'blah'
};
}
I have had problems in the past trying to test the values that are set outside the function. I think i tried setting it in the arguments. but it just didn't read. If you could also show me an example of using the variables some where else in the code like discussed above that will be helpful . I forgot to mention that the value of the variable will change when the user clicks on the box. either to true or false. I think my problem in the past is that when the box is checked and then uncheck I had a problem changing the variable especially when it is being used in a separate function
}
});
});
You can have an object with your vars and add vars to that object dinamically:
var oVars = {}
// adding a var
oVars[nameVar] = valueVar
// accessing the var
oVars[nameVar]
You can capture the id with the attr() or you can just change the value of the checkbox with val() method in jQuery like this: FIDDLE
$(document).ready(function () {
$('.checkboxes').change(function (event) {
if ($(this).is(':checked')) {
var captureId = $(this).attr('id');
$(this).val(true);
alert($(this).val());
}
else {$(this).val(false);
alert($(this).val());}
});
});
Note that you can evaluate later all the checkboxes with one button and collect the value false or true from them. Why would you go through all of the complications with changing values of variables.
The other two answers are correct, though it sounds like you're wanting to know generally how to manage a big list of checkboxes with differing methods depending on type. It could look like this:
function multiply(this_object){
if((this_object.is(':checked')) && (this_object.attr("with") == 1))
return "with withone and checked";
else
return "is not both";
}
$(document).ready(function(){
$('.checkboxes').click(function(){
var this_object = $(this);
alert(multiply(this_object));
});
});
There should be no need to store all of the values in a variable unless you are passing all of them to another page - eg., via AJAX. Just reference them straight from the source field. If you need other info stored alongside, make a new attribute on the field - like the "with" one that I made for this example. See this Fiddle: http://jsfiddle.net/6ug6gL97/
your question is quite broad; so I’ll try to do my best to give you some kind of answer. First of all I’d use variables of global scope when declaring variables: withones and withoutOnes. Secondly, you wanted to avoid repetition in your code. Well, for that purpose I’d use JavaScript Arrays. In an array, you can add your variables as objects. In an object you can have your ids and other data “packed” neatly in the array, which in turn helps your code to become efficient.
Below is an array with objects:
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
The above array can be used in your $('.checkboxes :checkbox').click(function() handler and add() function to avoid repetition. The updated code is below where jQuery's each() method is used for looping Array elements.
The last a bit of your question was related to add() function. Well, this was the tricky bit of your question, and I tried to use a callback function hopefully in the right way to execute your functions from the array. In the add method I tried to follow this answer: https://stackoverflow.com/a/13343452/2048391
About the last bit I’m not 100% sure did I use a callback function in the right way; so I hope someone more familiar with these tricky JavaScript functions can correct me, if something needs to be changed –thanks.
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
$(document).ready(function () {
$('.checkboxes :checkbox').click(function () {
var id = this.id;
var checkedValue = this.checked;
$.each(objectArray, function (index, object) {
if (object.id === id) {
object.checked = checkedValue;
}
});
add();
});
function add() {
// clear results
$("#addResults").text("");
$.each(objectArray, function (index, object) {
if (object.checked === true) {
var returnValue = createCallback(object.method)
$("#addResults").append(returnValue + "<br>");
console.log(returnValue);
}
});
}
function createCallback(method) {
return method();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="withones"></input>
<label>With Ones</label>
<br>
<input type="checkbox" id="withoutOnes"></input>
<label>Without Ones</label>
</div>
<div id="addResults">
</div>

Set global variable within anonymous function

I want to query a value from a script and use the value as variable for further functions. This code returns zero despite a value is set.
var total = 0;
var jqxhr = $.getJSON("number.php?jsonp=?", function(data) {
total = data[0]['Total']; // e.g 1234567
});
alert (total); // gives zero
I read that the problem could be with the asynchronous call and that my alert is executed before the anonymous function. I also tried to use some kind of setter function but withous success.
How can I set the global variable total?
Edit:
I now tried to use deferred objects / promises. I still have the problem that I need the value from the AJAX call before I initialise my counter. I cannot create the counter object in the done section because I cannot later change the value of the counter (still no global variable). Currently I have this:
var counter = $('.counter').jOdometer({
counterStart: '0',
numbersImage: '/img/jodometer-numbers-24pt.png',
widthNumber: 32,
heightNumber: 54,
spaceNumbers: 0,
offsetRight:-10,
speed:10000,
delayTime: 300,
maxDigits: 10,
});
function update_odometer() {
var jqxhr = $.getJSON("/number.php?jsonp=?")
.done(function(data){
console.log(data);
total = data['Total'];
counter.goToNumber(total);
})
.fail(function(data){
console.log(data);
});
};
update_odometer();
setInterval(update_odometer, 60000);
If I initialize the counter with zero then there is a strange start animations which jumps up and down. If I could get the real number instead of zero everything would work fine. Or should I completely switch to a synchronous call? How would I do that? Or are callbacks the better solution?
Took me a while to understand your problem. Still I'm not sure whether this would help or not.
var counter = null;
function update_odometer() {
var xhr = $.getJSON("/number.php?jsonp=?").done(function(data) {
if (counter === null) {
var counter = $('.counter').jOdometer({
counterStart: data['Total'],
numbersImage: '/img/jodometer-numbers-24pt.png',
widthNumber: 32,
heightNumber: 54,
spaceNumbers: 0,
offsetRight:-10,
speed:10000,
delayTime: 300,
maxDigits: 10,
});
} else {
counter.goToNumber(data['Total']);
}
});
}
If I were you I would look into library code and rectify the strange animation for zero start value. And I understand that you are not afraid to do that.

Store jquery function on variable

I have this code in .js file:
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function (data) {
if (data.address.country='spain') {
var a="http://www.link1.com";
} else {
var a="http://www.link2.com";
}
return a;
});
var fan_page_url = data();
How can I store var a in var fan_page_url ?
Thank you very much.
Try getting rid of a and assigning the links directly.
var fan_page_url;
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
if (data.address.country = 'spain') {
fan_page_url = "http://www.link1.com";
} else {
fan_page_url = "http://www.link2.com";
}
});
You have two options: assigning the external variable directly, as depot suggested, or treating the $.getJSON return value as a Deferred:
$.when($.getJSON(...)).done(function(returnValue) {
fan_page_url = returnValue;
});
The latter is useful in case you don't want to hardcode the variable you'll store the results (though in general it's not a problem, and the former option is easier/cleaner).
It's an old question on which I just stumbled (looking for something slightly different) but as answers did not seem to hit the nail on the head, I thought I'd add 2 cents: if you (op) had success with a variable that was hardcoded and set manually in config.js, that you were able to grab from start.js, why not simply:
keep the variable declared like you did in the global scope
assign it a default or null or empty value:
var fan_page_url = null; // or
var fan_page_url = ''; // or
var fan_page_url = 'http://url_default'; // etc...
then update the global variable inside the json function:
$.getJSON('http://api.wipmania.com/jsonp?callback=?', function(data) {
if (data.address.country='spain') {
fan_page_url = "http://url1";
} else {
fan_page_url = "http://url2";
}
});
in your start.js page, you can always perform a check to see if the variable is set or not, or still carries it's default value or not and act accordingly...
It is likely that if it used to work with your normally, manually declared variable, it would work the same here as you would have changed nothing structurally, only would be updating the variable after the json response.
Answer posted for the posterity, it may help someone in the future.

Categories

Resources