can't set variable to a outer function [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I can't seem to be able to set this.chkOK inside my ajax function. I'm sorta clueless how I go about doing this so I thought maybe calling validateFields.call(this) should of fixed my problem but I found out that wasn't the case. So I'm sorta lost what to do for my next step. I don't want to set this to a global variable unless I have to. I'm trying to set this.chkOK = true
function validateFields() {
this.chkOK = null;
this.username = function() {
if(FS.gID('username').value.length >= 2) {
var user = FS.gID('username').value;
//Make sure that the username doesn't already exist
FS.ajax('/server/chkUser.php?user='+user,'GET',function(){
validateFields.call(this);
if(xmlText == 0) {
this.chkOK = true;
alert("This user doesn't exist.");
}
else if(xmlText == 1) {
alert("Theres already a user with this username");
this.chkOK = false;
}
});
}
else {
alert("empty");
this.chkOK = false;
}
alert(this.chkOK);
}
}

The value of this in your example is NOT the function inside which it's declared, like you assume in your code.
If you simply use var chkOK = null; instead of this.chkOK = null; it should start to work.

It is because this inside the FS.ajax is not the same with this you intended to work with. this in FS.ajax means this of FS
You may assign this into another variable and use it inside FS.ajax. For example,
Note: Unless you know the reason why you put this.chkOk inside the function (such as expected validateFields be invoked by call or
apply) this is global object (which you don't want to) or
undefined in strict mode which will cause the code to fail
function validateFields() {
this.chkOK = null;
// ** assign this to that. So you can reference it inside FS.ajax **
var that = this;
this.username = function() {
if(FS.gID('username').value.length >= 2) {
var user = FS.gID('username').value;
//Make sure that the username doesn't already exist
FS.ajax('/server/chkUser.php?user='+user,'GET',function(){
validateFields.call(this);
if(xmlText == 0) {
that.chkOK = true; // use `that` instead of `this`.
alert("This user doesn't exist.");
} else if(xmlText == 1) {
alert("Theres already a user with this username");
that.chkOK = false; // use `that` instead of `this`
}
});
} else {
alert("empty");
this.chkOK = false;
}
alert(this.chkOK);
}
}

Related

How do I pass a context into a Javascript promise [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I will be the first to admit, I don't always get JS Promises. So if this is a stupid question I apologize in advance. =) Given the code below, I need to set a property in the class that contains this function (i.e. I need to call "this" within the fullfullment methods and have it refer back to the class.
I saw a few things that related to setting context, but they also required closures (()=>{...code..}) which don't work so well in Internet Explorer. And we can hate on that browser all we want but at the end of the day its a requirement that this code works in IE.
So my question today is, how do I get a reference to this passed into the methods below?
var result = this.saveChanges();
return Promise.resolve(result).then(function (value) {
return value.HasError === false;
}, function (value) {
if (value && value.responseJSON) {
return value.responseJSON.HasError === false;
}
return false;
});
Your assistance is appreciated immeasurably.
You can declare a variable that references this and use that in the function.
var self = this;
var result = this.saveChanges();
return Promise.resolve(result).then(function (value) {
self.someProperty = true;
return value.HasError === false;
}, function (value) {
if (value && value.responseJSON) {
return value.responseJSON.HasError === false;
}
return false;
});

replace javascript function with a new function [duplicate]

This question already has answers here:
Can you alter a Javascript function after declaring it?
(12 answers)
Closed 6 years ago.
In our ordering system there is an embedded function I have no access to at all. Conveniently there is a spelling error in it so when a user clicks something a popup appears and has grammar issues in it.
Is there a way for me to replace that text or replace the function with a new function that has all the same code but correct spelling?
This is the function I need to edit.. note confirm says 'You selection' not 'Your selection'
I'd prefer to replace the whole thing because I may want to do some other edits but for now I'd like to fix that spelling error.
function showProof()
{
var blnSubmit = false;
var strHid='';
var strSave='';
if (aryTemplateChoices.length == 0)
{
blnSubmit = true;
}
else
{
for (var i=1; i<=aryTemplateChoices.length; i++)
{
strSave = aryTemplateChoices[i-1];
if (strSave=='')strSave='0';
if (document.getElementById('hidctrl'+ i))strHid = document.getElementById('hidctrl'+ i).value;
if (strHid=='')strHid='0';
if ((strSave != '0') && (strHid != strSave))
{
blnSubmit = true;
break;
}
}
}
if (blnSubmit)
{
if (confirm('Your selection has changed, do you want to save?'))
{
document.getElementById('subtype').value = 'proof';
document.getElementById('prevclick').value = '';
document.getElementById('frm1').submit();
}
}
canAddToCart();
//<!--WRITE-->
getQuantityPrice()
//<!--/WRITE-->
loadProof();
}
It doesn't really matter where the original function is and how you access it, as long as you just redefine the function (with the same name and corrected code) at a scope closer to where you want to use it.
Here's an example:
function foo(){
console.log("ORIGINAL foo says hello.");
}
function foo(){
console.log("NEW foo says hello.");
}
// The second declaration is in the same scope as the first, but it comes after the first
// so it overwrites that declaration and the second one is the one that is used.
foo();

return statement in forEach won't stop execution of function [duplicate]

This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Closed 2 years ago.
I am trying to determine whether or not an array holds a certain item. If it does, I would like to hold the function, otherwise it should get added.
function addPacking(item){
data.packings.forEach(function(entry){
if(item.name == entry.name){
return;
}
});
data.packings.push(item);
}
Unfortunately, the data is pushed even when the if condition is met. How do I prevent this behaviour without using an else condition?
(I do not want to use else because my actual code is a lot more complex than this and I'd like to keep it readable)
Edit:
Does forEach execute asynchronously?
Old ways are sometimes the best. It's because you're passing a delegate function when calling .forEach. The return within the delegate is getting lost, and isn't applying to anything. To get your desired result, you'll want to exit the calling function addPacking. This can be done using a simply for loop.
function addPacking(item){
for (var i = 0; i < data.packings.length++; i++) {
if (item.name == data.packings[i].name) {
return;
}
}
data.packings.push(item);
});
This approach also supports older browsers, unlike some, every and forEach
You can't stop forEach execution other than throwing an exception (#Yoshi). Which should not be considered as an option to affect program code flow (#Me).
What you can do is to use another method some or every
function addPacking(item){
var contains = data.packings.every(function(entry){
return item.name != entry.name;
});
if(contains) {
data.packings.push(item);
}
}
Or
function addPacking(item){
var conatins = !data.packings.some(function(entry){
return item.name == entry.name;
});
if(contains) {
data.packings.push(item);
}
}
OLD question but in case someone else comes across this thread.
If you are using ECMAScript 6 you can use the Array find() method
var found = myArray.find(function (element) { return element === arrayToFind; });
so for this particular scenario would be:
function addPacking(item){
var foundItem = data.find(function(entry){ return entry.name == item.name});
if (foundItem) data.packings.push(foundItem);
}
see http://www.w3schools.com/jsref/jsref_find.asp for another worked example.
Return just aborts the function called in forEach, not your addPackings function.
function addPacking(item){
var isInPackings = false;
data.packings.forEach(function(entry){
if(item.name == entry.name){
isInPackings = true;
}
});
if (!isInPackings)
data.packings.push(item);
}
Yo are just returning from the child function but not from the parent function
function addPacking(item){
var check=false;
data.packings.forEach(function(entry){
if(item.name == entry.name){
check=true;
return;
}
});
if (check) return;
data.packings.push(item);
}

best way to toggle between functions in javascript?

I see different topics about the toggle function in jquery, but what is now really the best way to toggle between functions?
Is there maybe some way to do it so i don't have to garbage collect all my toggle scripts?
Some of the examples are:
var first=true;
function toggle() {
if(first) {
first= false;
// function 1
}
else {
first=true;
// function 2
}
}
And
var first=true;
function toggle() {
if(first) {
// function 1
}
else {
// function 2
}
first = !first;
}
And
var first=true;
function toggle() {
(first) ? function_1() : function_2();
first != first;
}
function function_1(){}
function function_2(){}
return an new function
var foo = (function(){
var condition
, body
body = function () {
if(condition){
//thing here
} else {
//other things here
}
}
return body
}())`
Best really depends on the criteria your application demands. This might not be the best way to this is certainly a cute way to do it:
function toggler(a, b) {
var current;
return function() {
current = current === a ? b : a;
current();
}
}
var myToggle = toggler(function_1, function_2);
myToggle(); // executes function_1
myToggle(); // executes function_2
myToggle(); // executes function_1
It's an old question but i'd like to contribute too..
Sometimes in large project i have allot of toggle scripts and use global variables to determine if it is toggled or not. So those variables needs to garbage collect for organizing variables, like if i maybe use the same variable name somehow or things like that
You could try something like this..: (using your first example)
function toggle() {
var self = arguments.callee;
if (self.first === true) {
self.first = false;
// function 1
}
else {
self.first = true;
// function 2
}
}
Without a global variable. I just added the property first to the function scope.
This way can be used the same property name for other toggle functions too.
Warning: arguments.callee is forbidden in 'strict mode'
Otherwise you may directly assign the first property to the function using directly the function name
function toggle() {
if (toggle.first === true) {
toggle.first = false;
// function 1
}
else {
toggle.first = true;
// function 2
}
}

when to use var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript: is using ‘var’ to declare variables optional?
how come in this code example below when i put var before the variables it does not work, however if i remove the var it works? i thought you had to use var when you were creating new variables.
function myfunction () {
if (document.getElementById('ramyes').checked) {
var itischecked = "yes"
} else if (document.getElementById('ramno').checked) {
var itischecked = "no"
}
}
function display () {
myfunction()
if (itischecked == "yes") {
alert ("it sure is");
} else if (itischecked == "no") {
alert ("it is not");
}
}
If you use var, the variable is only visible inside the current function (it's a local variable). If you don't use var when first setting the variable, it creates a global variable, which is visible to all functions.
Defining global variables by just setting them is usually frowned upon because most of the time you want local variables (in your case you should return your "itischecked" value from the function, instead of storing it in a global variable), and setting a variable without var looks like a mistake. It is also an error in strict mode (which everybody should use, always). To explicitly define a global variable in (browser) JS, use window.variableName, or var in the global scope (outside any functions).
But before you do that, think carefully whether that's a good idea. The more global variables you have, the higher the chance you will get a name collision when multiple scripts use the same variable name.
You should use var when you create a variable, but if you want to use the same variable in two functions, the variable has to be created in a scope outside both functions:
var itischecked;
function myfunction () {
if(document.getElementById('ramyes').checked) {
itischecked = "yes"
} else if(document.getElementById('ramno').checked) {
itischecked = "no"
}
}
function display () {
myfunction();
if (itischecked == "yes") {
alert ("it sure is");
} else if (itischecked == "no") {
alert ("it is not");
}
}
If you create a variable inside a function, that becomes a local variable. It is only visible inside that function, and goes away when you return from the function.
In your case you should rather use the return value of the function instead of putting a value in a variable. That way it is easier to follow how the data flows in the program, and you don't need to create a global variable:
function myfunction () {
if(document.getElementById('ramyes').checked) {
return "yes"
} else if(document.getElementById('ramno').checked) {
return "no"
}
}
function display () {
var itischecked = myfunction();
if (itischecked == "yes") {
alert ("it sure is");
} else if (itischecked == "no") {
alert ("it is not");
}
}
Just to add to the previous answer that suggests you shouldn't create global variables: to avoid doing so, you need in some way to make a larger scope so that variables can be shared between your two functions. That's where the var comes. For instance:
function myProgramme() {
var itischecked;
function myfunction() {
if (document.getElementById('ramyes').checked) {
itischecked = "yes"
}
else if (document.getElementById('ramno').checked) {
itischecked = "no"
}
}
function display() {
myfunction()
if (itischecked == "yes") {
alert("it sure is");
}
else if (itischecked == "no") {
alert("it is not");
}
}
}​
(Although in your specific example you could more simply have myfunction pass itischecked to display as a return value.)

Categories