javascript variable scope binding using angularjs - javascript

I am using angularjs/javascript code for image Uploading but i got stuck in variable binding , can anyone help me out, here is my code.
var image_source;
$scope.uploadedFile = function(element) {
reader.onload = function(event) {
image_source = event.target.result;
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
console.log(image_source,event.target.result, element.files[0], "***not working here***");
I'm binding varibale named image_source within function but when i access this outside the function it always return undefined why ?
PS:- i can get this in the typescript using phatarrow operator but how to do in javascript i dont know

If your console.log statement is called before $scope.uploadedFile which is most likely to be the case, the value will not be set, I suggest you try to call the function and put your console.log statement at the end of the function, inside the block.
That's not an angular issue but more like javascript, when you declare an anonymous function it's not called immediately
let mynumber = 1
let myfunction = () => {
mynumber = 2
}
console.log(mynumber) // 1
myfunction()
console.log(mynumber) // 2

Related

JS - Calling function from function not working

I have a function that gets called, and in it, I call another function called:
updatePerson(name)
For some reason it never activates when the function below is called. Everything else in the function works.
function updateName(name) {
$.get('XXX',function (data) {
var results = $.parseJSON(data);
var matchName = String(results.data[0].first_name);
updatePerson(matchName);}
);
};
Has anyone got an idea what I am doing wrong?
If I run alert(matchName) I get Nick as a response.
If I run console.log(updateMap(matchAddress)) I get undefined
It could do with the fact that you're passing a parameter from a callback function. In Javascript, variables inside a Callback are not available outside the callback.
Try setting the value of String(results.data[0].first_name) to a variable declared outside of the updateName function (i.e a global variable) and then call the updatePerson function outside of update name, with the globally declared variable as a parameter. Like so
var globalMatchName = '';
function updateName(name) {
$.get('XXX',function (data) {
var results = $.parseJSON(data);
globalMatchName =String(results.data[0].first_name);
}
);
updatePerson(globalMatchName)
}

On passing argument to a callback function

I have some ambiguity in Javascript callback functions.
The first code is structured as follows:
function firstFunction()
{
var message = "something";
secondFunction(message);
}
function secondFunction(message)
{
var myButton = document.getElementById("my-button");
myButton.addEventListener('click',thirdFunction(message));
}
function thirdFunction(message)
{
console.log("the messages is: "+message);
}
When I run the script above, the thirdFunction gets executed without clicking the button.
After some research, I read about the closure in Javascript. Then I changed the code to the following structure:
function firstFunction()
{
var message = "something";
secondFunction(message);
}
function secondFunction(message)
{
var myButton = document.getElementById("my-button");
myButton.addEventListener('click',thirdFunction);
}
function thirdFunction(message)
{
return function(){
console.log("the messages is: "+message);
}
}
I got the expected result. The thirdFunction is executed only when the button is clicked.
I am not sure if I my second code structure is correct? I am not sure if I'm getting the closure concept correctly as I never returned a function in conventional programming before. This is a new concept to me. Please, correct me if I'm wrong.
EDIT:
Some of the solutions suggest writing it like this:
myButton.addEventListener('click', function() { thirdFunction(message) });
For code readability, I am trying to avoid this. I prefer to place the code for the thirdFunction outside the secondFunction.
Use an anonymous function to make the closure in the correct environment:
function secondFunction(message)
{
var myButton = document.getElementById("my-button");
myButton.addEventListener('click', function() {
thirdFunction(message)
});
}

Recall a function without re-initializing every time

I'm trying to call a function without re-initializing (hope I used the correct word here) it every time I call it. So the first time it gets called, it should initialize, but after its initialized, it should just use that reference.
Here's the code I'm trying to do it with.
JSFiddle
console.clear();
function mainFunction(e) {
var index = 0;
function subFunction() {
console.log(index++);
}
return subFunction();
}
window.addEventListener('click', mainFunction)
index should increase by one every time mainFunction gets called. The obvious solution, is to make index a global variable (or just out of mainFunction). But I need index to stay inmainFunction`.
How can I make index increment every time (using the same reference) mainFunction gets called?
I tried assigning mainFunction to a variable, then calling the variable in the event listener,
var test = mainFunction;
window.addEventListener('click', test)
but that didn't work. The results were the same.
You should correct the code as follows;
console.clear();
function mainFunction(e) {
var index = 0;
function subFunction() {
console.log(index++);
}
return subFunction; // <<< don't invoke subfunction
}
window.addEventListener('click', mainFunction()) // <<< invoke mainfunction
maybe try closures?
var main = (function () {
var index = 0;
return function () {return index += 1;}
})();
main()
main()
//index should be 2...
explain-
The variable main is assigned the return value of a self-invoking function.
The self-invoking function only runs once. index initialize only once.
If you don't want to make index global (or one scope higher regarding mainFunction), you can use a closure:
var mainFunction = (function () {
var index = 0;
return function () {return console.log(index++);}
})();
<button onclick="mainFunction()">Click</button>
Using OOP concept is the proper way to achieve this. The following should help you.
If you want to do it in ES6 way follow this babel example
var mainFunction = function(val) {
this.index = val //initialize this with the fn parameter or set a atatic value
}
mainFunction.prototype.subFunction = function() {
return this.index++
}
var instance = new mainFunction(0)
window.addEventListener('click', function() {
console.log(instance.subFunction())
})
<p>Click to see the result </p>

Function not defined in Javascript Console

I don't know why my function in the console shows not defined. I have tried to make it right and I just can't seem to get it. It works fine until I try to use the setInterval function. Also the build keeps saying I am missing a semicolon, but I just don't see it.
$(document).ready(function () {
var machineDataViewModel = {
machineDataItems: ko.observableArray([]),
loadMachineDataItems: function DataLoad() {
machineDataViewModel.machineDataItems.length = 0;
$.getJSON("http://localhost/JsonRestful/Service1.svc/GetMachineData", function (data) {
$.each(data.GetMachineDataResult, function (index, item) {
machineDataViewModel.machineDataItems.push(new machineDataModel(item));
});
});
}
};
ko.applyBindings(machineDataViewModel);
machineDataViewModel.loadMachineDataItems();
setInterval(DataLoad, 9000);
});
function machineDataModel(item) {
this.mach_no = ko.observable(item.mach_no),
this.VAR1 = ko.observable(item.VAR1),
this.VAR2 = ko.observable(item.VAR2),
this.VAR3 = ko.observable(item.VAR3),
this.VAR4 = ko.observable(item.VAR4)
};
You can't define the DataLoad() function the way you are and expect it to be available in your setInterval(). It simply doesn't work that way. The symbol DataLoad is only available inside the scope of that function. Instead, you can call it as:
setInterval(machineDataViewModel.loadMachineDataItems, 9000);
Here's a simple demonstration that shows you can't name your function like you are and expect to use that name outside that scope: http://jsfiddle.net/jfriend00/6t0pp60s/ (look in the debug console to see the error).
FYI, if you need your function to have the right value of this (which I don't think you actually do), then you would call it like this (with a semi-colon at the end of every line):
setInterval(machineDataViewModel.loadMachineDataItems.bind(machineDataViewModel), 9000);
As for the semicolon issue, jsHint points to the this.VAR4 assignment line. I'd suggest changing machineDataModel() to this (which gives you a clean bill of health in jsHint):
function machineDataModel(item) {
this.mach_no = ko.observable(item.mach_no);
this.VAR1 = ko.observable(item.VAR1);
this.VAR2 = ko.observable(item.VAR2);
this.VAR3 = ko.observable(item.VAR3);
this.VAR4 = ko.observable(item.VAR4);
}

explain javascript: value assignment fails

var sc = new stuCore();
function stuCore() {
this.readyPages = [];
this.once = true;
var self = this;
// gets called asynchronously
this.doPrepPage = function (page){
if(self.once == true){
// still gets executed every time, assignment fails
self.once = false;
doSomeStuffOnce();
}
};
this.addReadyPage = function (pageid) {
console.log("readypage called");
this.readyPages.push(pageid);
if (!$.inArray(pageid, self.readyPages) != -1) {
this.doPrepPage(pageid);
}
};
}
why does this assignment fail? I thought I knew the basics of js, but I'm stumped by this. And furthermore what would be a possible solution? call a constructor first and set the variable there?
EDIT:
gets called like this in some other script:
sc.addReadyPage(self.id);
The jQuery.inArray function will return the index in the containing array for the given value. Your script pushes pageid into this.readyPages before checking whether it exists in self.readyPages. this.readyPages and self.readyPages are the same array reference, so the result will always be zero or greater, so the condition that calls doPrepPage will never run.
You could try switching their order around:
this.addReadyPage = function (pageid) {
console.log("readypage called");
if ($.inArray(pageid, self.readyPages) != -1) {
this.readyPages.push(pageid);
this.doPrepPage(pageid);
}
};
(edit: Removed the additional !, thanks #chumkiu)
If I understand correctly you're calling this.doPrepPage as <insert variable name here>.doPrepPage?
If this is the case then your var self passes through to the anonymous function and is stored there, so everytime you call this.doPrepPage it takes the local variable of self.
Try setting self to a global variable, this way it will permanently modify self so each time this.doPrepPage is called it uses the updated variable.

Categories