Javascript closures and scope issues [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I can't wrap my head around javascript closures. I want 4 random numbers, but only get the the last one replicated 4 times.
Javascript
$(function() {
function setNewNumber(element) {
return function (newNumber) {
element.text(newNumber);
}
}
$('.number').each(function() {
$.get('http://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new',
setNewNumber($(this))
);
});
});
HTML
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
<div class="number"></div>
A working plunker example
Any hints?

The get request is being cached.
http://jsfiddle.net/hCEbd/1/
(That is to say your understanding of closures is correct and the code is working correctly).
From comments, because this is relevant:
You can request multiple numbers from random.org at the same timer per their API. Instead of using four requests, use num=' + $(".number").length and then do a little parsing

It's a little confusing what you're trying to achieve with your top functions. If all you want to do is set the new random number to the element, you don't need either of them.
Use ajax to specify a few parameters to your request. In particular, you want to stop caching of your request. You can also supply a context to reference your .number element.
$('.number').each(function() {
$.ajax({
type: "GET",
url: 'http://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new',
context: this,
success: function(data) {
$(this).text(data);
},
cache: false
});
});
This solution fiddle here.

Works: http://plnkr.co/edit/XTOI20kGbFbzdtDaqpLZ
Your request is being cached. By the way, getting data in cycle - it's not a good idea.

Any jquery ajax request, like $.get, changes the scope. If you want to reuse your setNewWord function it needs to be either be globally scoped or scoped in the result of the get.
Take a look at the jsfiddle.
http://jsfiddle.net/justengland/hJnXb/2/
function setNewWord(element) {
$('#output').append(element + '<br>');
}
$(function () {
$(numbers).each(function () {
var url = 'http://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new';
$.get(url, setNewWord);
});
});

Related

Printing string in JavaScript is giving error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to print 2 strings. What is wrong here?
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick=alpha("Peter", "Jack")>ok</button>
Others have already told you that the issue is that the value of your onclick needs to be quoted and those quotes should not conflict with the quotes you are already using around your function arguments, but I have a different approach for you....
You really shouldn't be using inline HTML event attributes (i.e. onclick) in the first place. This is a 25+ year old technique that just won't die because it's easy to understand and most new developers just copy someone else's code and convert it to their needs. There are many reasons why this old technique should just fade away and instead, you should use the modern API for event binding, which is .addEventListener().
In your case, it's not obvious why a button would have function arguments hard-coded into it, but if that really is your use case, those should be stored as data-* attributes.
Here's your scenario, reworked into code from this century:
// Get a reference to the DOM element you need to work with
let btn = document.querySelector("button");
// Get the data-* into an array
let people = btn.dataset.people.split(",");
// Do the event binding in JavaScript, not HTML
// We'll set the click event to invoke an anonymous
// function that itself calls the real function and
// passes the proper arguments.
btn.addEventListener("click", function(){
alpha(people[0], people[1]);
});
function alpha(name1, name2){
console.log(name1, name2);
}
<!-- Notice that the data is held in a data-* attribute and
that the code to hook up the event is gone from the HTML. -->
<button data-people="Peter,Jack">ok</button>
You are wrongly defining the handler of onclick.
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick="alpha('Peter', 'Jack')">ok</button>
You are missing a pair of quotes.
<button onclick="alpha('Peter', 'Jack')">ok</button>
You need quotation marks around the function in HTML
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick="alpha('Peter', 'Jack')">ok</button>
Using Single quotes '' in the html instead of double will solve the issue. Also put quotes around the function
function alpha(name1, name2){
console.log(name1, name2);
}
<button onclick="alpha('Peter', 'Jack')">ok</button>

How should this querystring value be formatted in ajax input [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am modifying a code example that I will use (and not very familiar with Javascript)
This is the piece of code
function chk() { cnt++;
var resp=ajax('chk.php', 'POST', 'ordernr='XXXXXX'&r='+((new Date()).getTime()));
if (resp=='3') {
I am posting to this file withe a Querystring-varaible named ordenr
What is the correct syntax to enter the value of Querystring.ordernr instead of XXXXXX
var orderNumber = 1;
var requestParamsStr = 'ordernr=\'' + orderNumber + '\'&r=' + ((new Date()).getTime());
console.log(requestParamsStr);
function chk() {
//cnt++;
var resp = ajax('chk.php', 'POST', encodeURIComponent(requestParamsStr));
//rest of code
}
I think I understand your question. If you need to put quotes around the order number then you must use the escape character / the way I'm doing in the code snippet, so that it doesn't delimit the string (or, alternatively, you could use double quotes within the single quotes). You must also use + to concatenate the the strings.
UPDATE:
I've encoded the request param string as per #ADyson's comment.

alert dialog does not work for button click function jquery [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to add two actions in one button click, one handle form post another to show alert , the one for post works but the one to show alert doesn't .and when i try another action inside this button click does not work too
$('plot_marker').click(function () {
$.post('/searched/', $('mapform').serialize(), function (data) {
},
'json' // I expect a JSON response
);
alert("Hello!");
});
Unless you're using Web Components or some other framework, you almost certainly meant $('#plot_marker') or $('.plot_marker').
In your sample code you have used the is a tag selector which is a valid query selector used for selecting tags by name, but that was likely not your original intent.
In the below code, unless 'plot_marker' is a tag name, it should either be '#plot_marker' or '.plot_marker' depending on whether it is an id or a class.
$('plot_marker').click(function () {
$.post('/searched/', $('mapform').serialize(), function (data) {
},
'json' // I expect a JSON response
);
alert("Hello!");
});

Why do i have to enclose jQuery commands in a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm currently working my way through Learning jQuery by Karl Swedberg where all jQuery code samples in the book are contained in $(document).ready().
While i understand why the code has to be contained in $(document).ready(),namely so that they will be run only when the HTML document has loaded, the book does not explain why any code has to be placed inside a function.
E.g
$(document).ready(function(){
alert("The page has loaded.");
alert("2nd alert.");
});
In the example above, why does the alert have to be contained in a function() to work, and cannot an example like the one below will not work.
$(document).ready(
alert("The page has loaded.");
alert("2nd alert.");
);
I would appreciate if anyone can enlighten me.
Reads Docs, it specify a function to execute when the DOM is fully loaded.
.ready( handler )
Where, handler
Type: Function()
A function to execute after the DOM is ready.
$(document).ready accepts a callback. A callback is a javascript function. Javascript functions can be passed around just like variables. In the case above you are using an inline anonymous function, that is a function with no name.
You could rewrite your example like this:
function doStuff() {
alert("The page has loaded.");
alert("2nd alert.");
}
$(document).ready(doStuff);
You need to use a function because you cannot pass statements as parameters to a function but you can pass a function.
Note if you don't want to have to type as much there is a shorthand notation that is functionally equivalent:
$(function() {
alert("The page has loaded.");
alert("2nd alert.");
});
or without the inline function:
function doStuff() {
alert("The page has loaded.");
alert("2nd alert.");
}
$(doStuff);
$(document).ready() expects a function. Your second example is actually a syntax error, since alert("The page has loaded."); alert("2nd alert."); is not a valid parameter list.
The reason you typically have to use $(document).ready() in jQuery is because you are usually interacting with DOM nodes (which aren't actually available in the DOM yet if your script happens to be at the top of the page). An alternative is to put your script at the bottom of the page, at which point all of the DOM nodes you need are available, and there's no need for the $(document).ready() wrapper.

Javascript best practices - where's the best place to define a helper function inside a loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What's a better practice, this:
myArray.forEach(function(item)) {
doSomething(item);
function doSomething(an_item) {
console.log(an_item);
}
}
or this:
myArray.forEach(function(item)) {
doSomething(item);
}
function doSomething(an_item) {
console.log(an_item);
}
Does the first example create multiple instances of the function, or does it create it just the first time through the loop?
Thanks for any insight!
myArray.forEach(function(item)) {
doSomething(item);
}
function doSomething(an_item) {
console.log(an_item);
}
this function is best because it will created only one time ;
and
myArray.forEach(function(item)) {
doSomething(item);
function doSomething(an_item) {
console.log(an_item);
}
}
is a bad due to every time function will create during loop process
The second. Use the second form (because the first form will slow down your user's experience, which may well be a phone or low powered device), or the even shorter form
myArray.forEach(doSomething);
function doSomething(element, index, array) {
console.log("myArray[" + index + "] = " + element);
}
It really depends on the interpreter if your asking a pure question about performance, i would imagine some of the smarter ones would be good enough to not create and destroy the function each time if they never change during the loop but realistically thats what your telling it to do (Create the function each time as the scope is temporary) so don't be surprised if thats the case. imagine if for example you were dynamically creating a closure within the forEach, wouldn't each loop need to create a new copy of the function?
http://jsperf.com/closure-vs-name-function-in-a-loop/2
certianly I would imagine older browsers not being smart enough to know to only make it once.
another post: Don't make functions within a loop
I agree with what the others have said, and +1 on the second solution. You don't ever want to define/create functions within loops.
**Bonus
If you're function has to do with an object within the forloop, you can use this in your helper instead of passing the object via a parameter:
Example:
var myArray = [{ a: 1 }, { a: 2 }, { a: 3 }];
myArray.forEach(function(item) {
doSomething.call(item);
});
function doSomething(item) {
console.log(this.a);
}
It is good practice to always define things in the smallest scope possible.
So when you don't need the function elsewhere, defining it in the loop which uses it is the best choice.

Categories

Resources