Get var from another function? - javascript

Hello im trying to get a variable from another function
Code:
$(document).ready(function() {
var totalFiles;
$(".filesUpload").on("change", function() {
var files = $(".filesUpload").prop("files");
var names = $.map(files, function(val) { return val.name; });
$("#uploadBar").modal('show');
var totalFiles = names.length;
});
$("#uploadBar").on("shown.bs.modal", function() { var test = totalFiles; alert(test); });
But right now i only get undefined on the totalFiles, but if i have a alert right after var totalFiles = names.length i get the right result, anyone knows what i can do and what am i doing wrong?
PS. I've checked other threads aswell and it still doesn't work.

Check your references to totalFiles. You have one declared globally and then declared it locally in $(".filesUpload").on("change", function() {.
This is what it needs to be :
$(document).ready(function() {
var totalFiles;
$(".filesUpload").on("change", function() {
var files = $(".filesUpload").prop("files");
var names = $.map(files, function(val) { return val.name; });
$("#uploadBar").modal('show');
totalFiles = names.length;
});
$("#uploadBar").on("shown.bs.modal", function() { var test = totalFiles; alert(test); });
Just remove 'var' from the 1st function.

Do not declare the variable twice. In your onChange function, just use totalFiles rather than declaring it again with the var keyword.
$(".filesUpload").on("change", function() {
...
totalFiles = names.length;
...
});

You are declaring a local variable inside your callback. totalFiles = names.length; is the right way to update the global variable.
var totalFiles;
$(".filesUpload").on("change", function() {
var files = $(".filesUpload").prop("files");
var names = $.map(files, function(val) { return val.name; });
$("#uploadBar").modal('show');
totalFiles = names.length;
});

Related

Javascript (unsolved) - Passing variables inside a function to an onclick function

I'm trying to pass a variable from an addEventListener function to an onclick function. Thank you!
document.getElementById('rect').addEventListener('keyup', function() {
var index = 5;
}
asd.onclick = function() {
}
Here is the way
asd.onclick = function() {
var index = 5;
hey(index);
}
function hey (index) {
var recive = index;
console.log(index);
}

How to make a prototype within a closure?

Here, I have this two code :
var mod = function() {
var a = function() {
this.fucname = 'hello';
};
a.prototype.build = function() {
return 'before '+this.fucname;
};
return new a();
};
for( var i=0; i<10000; i++ ){
var newfuc = mod();
};
and
var a = function() {
this.fucname = 'hello';
};
a.prototype.build = function() {
return 'before '+this.fucname;
};
for( var i=0; i<10000; i++ ){
var newfuc = new a();
};
After I check both in chrome dev, the second code take a JS HEAP 3.0MB,
the first code take a JS HEAP 10MB.
Is that mean, the build function has been created 10000 time in the first code? and how can I refine it without remove the cover mod?
I have to pass something into the function...
If you want to hide the constructor but also only evaluate it once, you can make use of an IIFE to create a new scope:
var mod = (function() {
var a = function() {
this.fucname = 'hello';
};
a.prototype.build = function() {
return 'before ' + this.fucname;
};
return function() {
return new a();
};
})();
for (var i = 0; i < 10000; i++) {
var newfuc = mod();
}

JS: How may I access a variable value inside a function that's inside another function, and that both functions belong to the same object?

In this example, how may I get the value of the i var inside the for loop, into guardarReserva() function?
guardarReserva() and generarGrilla() are both methods of the same myApp object.
var myApp = {
generarGrilla:function(){
for(var i=1; i<13; i++){
var impresionGrilla = $('#grilla').append("one");
};
},
guardarReserva:function(){
var reservaConfirmada = $('#horario').append("two");
},
You would need to define i outside of both functions:
var myApp = {
i:0,
generarGrilla:function(){
for(this.i=1; this.i<13; this.i++){
var impresionGrilla = $('#grilla').append("one");
};
},
guardarReserva:function(){
var reservaConfirmada = $('#horario').append("two");
console.log(this.i);//i is now accessible
},
You can also use a global variable:
var i;
var myApp = {
generarGrilla:function(){
for(i=1; i<13; i++){
var impresionGrilla = $('#grilla').append("one");
};
},
guardarReserva:function(){
var reservaConfirmada = $('#horario').append("two");
console.log(i);//i is now accessible
},

Correct scope reference to object within window object

Since my previous question was not answered i thought i give it another try only formulated better.
(function() {
var ns = {};
for(var i = 0; i < 2; i++){
ns['someName'] = 'na' + i;
//Logs ns0 and ns1 like i want
console.log(ns["someName"]);
window.addEventListener('load', function(){
//Logs ns1 twice
console.log(ns["someName"]);
});
}
})();
So the question being how to keep the correct scope within the window eventListener.
Thanks!
You can use the magic of closures
(function(value) {
window.addEventListener('load', function(){
//Logs ns1 twice
console.log(value);
});
})(ns["someName"]);
Defined an inline function and called it inmediatly using the current value for ns["someName"]
I simplified the code to show how you can 'preserve' the scope within each load-callback-function. You can use a self-execution function to return a closure:
(function() {
for(var i = 0; i < 2; i++) {
window.addEventListener('load', (function(i){
return function(evt) {
// i is as expected: 0 and then 1
console.log(i);
// the variable 'evt' contains the event-object
};
})(i));
}
})();
thank you all for your input much appreciated! ive been battling this for a two days now and i was about to pull out my hair.
here is the final code:
(function() {
for(var i = 0; i < 2; i++){
var ns = {};
ns['someName' + i] = 'ns' + i;
//Logs ns0 and ns1 like i want
console.log(ns);
(function(value) {
window.addEventListener('load', function(event){
//Logs ns0 and ns1 like i want
console.log(value);
//preseved my events
console.log(event);
});
})(ns);
}
})();
(function() {
var ns = {};
for(var i = 0; i < 2; i++){
ns['someName'] = 'na' + i;
console.log(ns["someName"]);
(function(value){
window.addEventListener('load', function(){
console.log(value);
});
}(ns['someName'] ));
}
})();
You can achieve it with the help of closures
(function() {
var ns = {};
for(var i = 0; i < 2; i++){
ns['someName'] = 'na' + i;
console.log(ns["someName"]);
(function(value){
window.addEventListener('load', function(){
return (function(){
console.log(value);
})()
});
}(ns["someName"]));
}
})();
This will do the trick :)

Storing variables in my name spaced javascript

If I have my name space for my app like so:
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
}).apply(myApp);
Then if I log the following result:
console.log(myApp.next()); //1
How can I store variable within the name space function, for instance something like:
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
var var1 = "One";
};
}).apply(myApp);
Trying to access like this:
console.log(myApp.variableStore().var1); // Gives me an error
Is this possible, or even a good idea? Or should I just declare a new name space for what are essentially global variables?
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
this.var1 = "One";
return this;
};
}).apply(myApp);
Such declaration will add var1 property to myApp object only after variableStore() is called:
myApp.var1 //undefined
myApp.variableStore() // Object {...}
myApp.var1 //"One"
About your question: you can not actually store variable within a function. If you are trying to make a internal namespace for myApp, consider doing the following:
(function() {
var id = 0;
this.next = function() {
return id++;
};
this.subNameSpace = {
init: function () {
this.var1 = "One"
return this;
}
}
}).apply(myApp);
myApp.subNameSpace.init();
myApp.subNameSpace.var1; //"One"
(function() {
var id = 0, var1; //DECLARE VARIABLE HERE
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
this.var1 = "One"; //NO "VAR" KEYWORD
};
}).apply(myApp);
Using var var1 = "One"; creates var1 in the local scope, so you can't access it from the instance of myApp. Also, remember to use this.var1; otherwise the variable var1 is essentially a private variable and can't be accessed from the outside.
Also, if you want to use
console.log(myApp.variableStore().var1);
Then you'll have to return myApp; in your variableStore method. This is because myApp.variableStore() currently returns nothing, so you can't access var1 of nothing. So, here is the complete code:
var myApp = {};
(function() {
var id = 0, var1;
this.next = function() {
return id++;
};
// Store variables here ...
this.variableStore = function() {
this.var1 = "One";
return myApp;
};
}).apply(myApp);
console.log(myApp.variableStore().var1);
You already got some answers on how you could use your variableStore function. But maybe it would be sufficient for you to just store your variable with the .-operator?
var myApp = {};
(function() {
var id = 0;
this.next = function() {
return id++;
};
}).apply(myApp);
//store:
myApp.var1 = "One";
//request:
console.log(myApp.var1); //One

Categories

Resources