Store jquery function on variable - javascript

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.

Related

Is it bad practice to instantiate variables inside of $(document).ready as opposed to globally declaring them?

I'm trying to avoid the use of global variables in my code, so I'm trying to use a work around by declaring them inside of $(document).ready and passing them as parameters to functions outside of $(document).ready, updating them, and then returning the updated value from those functions to manipulate the variables inside of $(document).ready.
Another way around this is to use hidden input fields to store variables but I also heard that was bad practice.
I'm wondering if I should just use global variables, do it the way I'm currently doing it, or use hidden input fields?
Below is a brief example of what I'm trying to accomplish. The variable validations is the variable I want to be able to use and update.
$(document).ready(function(){
var validations = [];
$('#inp').keypress(function(e){
if(e.which == 13){
e.preventDefault();
scanValidation(validations, function(valid){
validations = valid;
});
}
});
}):
function scanValidation(valid, cb){
var scanval = $('#inp').val();
if(valid.includes(scanval)){
//display error
}
else{
var validarr = valid.slice();
validarr.push(scanval);
var myData=JSON.stringify({ "name":"user1", "validations":validarr});
//Makes an ajax call to see if the sent array validarr is a valid request
apiCall(myData,'scanValidation',function(decoded) {
if (decoded.Status!="ERROR") {
valid = validarr;
}
else {
//display error
}
return(cb(valid));
});
}
}
Any variables declared within the immediately executed function below will NOT be in the global scope.
(function () {
var someVar = 'someValue';
$(document).ready(function() {
});
})();
Is it bad practice to instantiate variables inside of $(document).ready as opposed to globally declaring them?
No, not at all! Variables should always be declared in the scope they're needed in, nowhere else.
Another way around this is to use hidden input fields to store variables but I also heard that was bad practice.
I've never heard of that, but yes it definitely sounds like a bad practise. That's just the same as a global variable, but a global variable stored in the DOM for some odd reason.
I'm trying to avoid the use of global variables in my code, so I'm trying to use a work around by declaring them inside of $(document).ready and passing them as parameters to functions outside of $(document).ready, updating them, and then returning the updated value from those functions to manipulate the variables inside of $(document).ready.
That, admittedly, is a bit weird.
The easiest way to improve this is to move the function declaration inside the ready handler as well, and just access the variable there directly - with the additional bonus of not having a scanValidation global variable:
$(document).ready(function() {
var validations = [];
function scanValidation() {
var scanval = $('#inp').val();
if (validations.includes(scanval)) {
//display error
} else {
var validarr = validations.slice();
validarr.push(scanval);
var myData = JSON.stringify({"name": "user1", "validations": validarr});
// Makes an ajax call to see if the sent array validarr is a valid request
apiCall(myData, 'scanValidation', function(decoded) {
if (decoded.Status!="ERROR") {
validations = validarr;
} else {
//display error
}
});
}
}
$('#inp').keypress(function(e){
if(e.which == 13){
e.preventDefault();
scanValidation();
}
});
});
If you want to make scanValidation reusable, so that it could be called from other places as well with its own array, I would suggest to create a factory function that creates validators, each of which is a closure over its own array. That way, the array is declared where it belongs, so that the user of the function does not have to store the state for them:
function makeScanValidator(display) { // any other configuration
var validations = [];
// returns closure
return function scanValidation(scanval) { // take it as an argument
if (validations.includes(scanval)) {
display(/* error */);
} else {
var validarr = validations.concat([scanval]);
var myData = JSON.stringify({"name": "user1", "validations": validarr});
apiCall(myData, 'scanValidation', function(decoded) {
if (decoded.Status!="ERROR") {
validations = validarr;
} else {
display(/* error */);
}
});
}
}
$(document).ready(function() {
var validate = makeScanValidator(function display() { … });
$('#inp').keypress(function(e){
if(e.which == 13){
e.preventDefault();
validate(this.value);
}
});
});

Using closure for storing and retrieving data

I am trying to use closure for storing and retrieving variable at the same time.
I am using JSONP and callback to the function
http://freegeoip.net/json/?callback=geoIPInfo
Closure
function geoIPInfo(newGeoData) {
var geoInfo;
if (newGeoData) {
geoInfo = newGeoData;
}
var provideGeoData = function () {
return geoInfo;
};
return provideGeoData();
}
I want firstly to store data and than retrieve last saved data from the closure using simple call like that
geoIPInfo()
If argument provided it will set new info otherwise it will return existing one.
But in my case data is set successfully, but when I try to get set data I get undefined
$("#super_button").click(function (e) {
alert(geoIPInfo());
e.preventDefault();
});
What is wrong with my closure understanding ?
Please explain.
Thank you.
This will work. The idea here is we create a function that returns a function with that accepts a parameter and we store geoInfo in a closure to keep it value. Idk if that makes sense, if you need a better explanation I can give it another try :)
var geoIPInfo = function() {
var geoInfo;
var provideGeoData = function (newGeoData) {
if (newGeoData) {
geoInfo = newGeoData;
}
return geoInfo;
};
return provideGeoData;
}();
Each time you call geoIPInfo(), you're re-declaring the local variable geoInfo. You'll want to declare geoInfo once, and have it accessible to geoIPInfo() via a closure:
//Create a closure
var geoIPInfo = (function(){
//Private variable, available via closure
var geoInfo;
function geoIPInfo(newGeoData) {
if (newGeoData) {
geoInfo = newGeoData;
}
var provideGeoData = function () {
return geoInfo;
};
return provideGeoData();
}
return geoIPInfo;
})();
alert(geoIPInfo()); //undefined
geoIPInfo('Some Data');
alert(geoIPInfo()); //'Some Data'
Here, we're creating a closure using an Immediately-Invoked Function Expression (IIFE).

Multiy String Variable Names Not Working In Javascript

Recently I posted about Dynamic Names in Javascript. I went ahead and tried to make a multi string variable name (combining a string and a variable to make a new variable name), and it does not seem to work. I am very confused because I am doing what many posts on SO say to do (so I think anyhow).
Anyhow here is the dynamic variable I am using:
var dynamic["replyupvote"+replyid] = false;
and then when I am calling it I use:
dynamic["replyupvote"+replyid]
So my question is where am I going wrong? If you would like to see my full code:
function replyupvote(replyid, upvotes, downvotes, votesclass, votesnumber) {
var dynamic["replyupvote"+replyid] = false;
return function() {
if (dynamic["replyupvote"+replyid]) {
dynamic["replyupvote"+replyid] = true;
}
else {
$.ajax({
url: "http://localhost/postin'/categories/votes.php",
type: "POST",
data: { 'itemid': replyid,
'userid': <?php echo $_SESSION["logged_in"]; ?>,
'action': "upvotes",
'type': "reply" },
success: function() {
$("." + votesclass).css("color", "orange");
$("." + votesnumber).text(parseInt(upvotes - downvotes) + 1);
}
});
dynamic["replyupvote"+replyid] = true;
}
}
}
This code worked before I through in the Multi String Variable Names. So what am I doing wrong? Thank You! :)
EDIT
I thought I should throw this in. Javascript throws the error that the function is not defined because of the incorrect syntax.
Regardless if what you are doing here makes sense or not, to dynamically create properties on an object, you will need to make sure JS knows it's an object, not an array. So before you try to create a dynamic object property, explicitly declare dynamic as an object:
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
That should get rid of the syntax error at least.
You would have to set dynamic as an object first
var dynamic = {};
dynamic["replyupvote"+replyid] = false;
variableName[keyName] = value; is the syntax of an object.
You have to tell js that your variable is an object before you can use this notation.

how to get a property name which represent a function in JS

This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc

remembering a javascript var each call to function

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);
}
}());

Categories

Resources