Passing parameters to function in CasperJS's evaluate - javascript

How can I pass a parameter to a function within CasperJS's evaluate?
//Should be logged in at this point
casper.then(function() {
var counter = 0;
var cap = 500;
this.evaluate(function(counter) {
var children = $('.companies-using-service').children();
while (counter < children.length) {
child = children[counter];
console.log($(child).find('a').attr('data-hint'));
counter++;
}
}, counter);
});
};
var scrapeClients = function(counter) {
var children = $('.companies-using-service').children();
while (counter < children.length) {
child = children[counter];
console.log($(child).find('a').attr('data-hint'));
counter++;
}
}
Above, I am able to pass parameters in using an unamed function. However, I wish to pass in the function scrapeClients to the evaluate function. In that case, I tried the following this.evaluate(scrapeClients(counter), counter). However, this does not work and the error says that it could not find $ variable.

Functions are first-class citizen in JavaScript. You can treat them in the same way as variables. You can pass them around. This means that you don't want
this.evaluate(scrapeClients(counter), counter)
but rather
this.evaluate(scrapeClients, counter)
In the first case, you're actually calling the function directly. Since the function uses some page properties that are only available inside of casper.evaluate, this will throw an error and stop the script.

Related

why is javascript parameter undefined?

I'm getting the error that "txtname" is undefined.
let i = 0;
let txtOne = 'Hi';
let txtTwo = 'My name is Sarah';
let txtThree = "and I'm learning web development";
let speed = 200;
let firstdiv = document.querySelector(".firstOne");
let nextdiv = document.querySelector(".nextOne");
let lastdiv = document.querySelector(".lastOne");
function typeWriter(txtname, divname) {
if (i < txtname.length) {
divname.innerHTML += txtname.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
window.onload = typeWriter(txtOne, firstdiv);
firstdiv.addEventListener("animationend", typeWriter(txtTwo, nextdiv));
nextdiv.addEventListener("animationend", typeWriter(txtThree, lastdiv));
Why is txtname coming up as undefined? Shouldn't it get replaced by whatever I pass as an argument in my typeWriter function?
Why isn't the typeWriter function looking at txtOne.length or txtTwo.length etc?
I'm still in the process of learning javascript so please excuse me if this is a basic error.
setTimeout(typeWriter, speed) means that in 200 ms, typeWriter will be invoked with no arguments. The arguments from the previous invocation are not carried forward automatically to the next invocation, you need to supply them. You can do so with an anonymous function:
setTimeout(function () { typeWriter(txtname, divname) }, speed)
While you're fixing this, you should probably also move state like i into the function, rather than depending on global state. You can do so by accepting i as an argument, but giving it a default value of 0:
function typeWriter(txtname, divname, i) {
i || (i = 0);
if (i < txtname.length) {
divname.innerHTML += txtname.charAt(i);
setTimeout(function () { typeWriter(txtname, divname, i + 1) }, speed);
}
}
This is a common pattern with recursive functions.
Another issue is the way you are setting the event handlers. You are actually setting the returned value of the typeWriter function as the event handler instead of the function itself. You should remove the invocation operator, i.e. window.onload = typeWriter, but since you want to call the function with specific parameters, you need to wrap the code with another function:
window.onload = function() { typeWriter(txtOne, firstdiv) };
firstdiv.addEventListener("animationend", function() { typeWriter(txtTwo, nextdiv) });
nextdiv.addEventListener("animationend", function() { typeWriter(txtThree, lastdiv) });

setInterval calling function with an undefined parameter

This question has been flagged as already answered with a link provided above. However, I already read that answer and it only answered how to use setInterval in a for loop. There were no functions being called with parameters passed to them in that solution, and that is my situation, so I couldn't use it to fix my situation.
I'm fairly new to programming, so I'll try to describe as best as I can. In setInterval, I am passing a parameter to the function toggleClusters which setInterval calls. The debugger shows the parameter as being correct. It is a reference to an array position that holds an object literal that contains map marker objects. I seem to be misunderstanding something about what values stay around and what do not when using setInterval, because the debugger shows the correct object literal being passed as an arg, but when the function is called, the debugger shows the obj that is supposed to be passed as undefined. Is it that this passed value no longer exists when the function is called?
function setClusterAnimations() {
for (var i = 0; i < clusters.length; i++) {
//intervalNames stores handle references for stopping any setInterval instances created
intervalNames.push(setInterval(function () {
//clusters[i] will hold an object literal containing marker objects
toggleClusters(clusters[i]);
}, 1000));
}
}
//cObj is coming back as undefined in debugger and bombing
function toggleClusters(cObj) {
var propCount = Object.keys(cObj).length;
for (var prop in cObj){
if (prop.getZIndex() < 200 || prop.getZIndex() == 200 + propCount) {
prop.setZIndex(200);
}
else {
prop.setZindex(prop.getZIndex() + 1)
}
}
}
This is typically the issue with such asynchronous calls as with setInterval(). You can solve this in different ways, one of which is using bind():
for (var i = 0; i < clusters.length; i++) {
//intervalNames stores handle references for stopping any setInterval instances created
intervalNames.push(setInterval(function (i) {
//clusters[i] will hold an object literal containing marker objects
toggleClusters(clusters[i]);
}.bind(null, i), 1000));
}
The toggleClusters(clusters[i]) statement will only be executed when your loop has finished, at which time i will be beyond the correct range (it will be clusters.length). With bind(), and mostly with the function parameter i, you create a separate variable in the scope of the call back function, which gets its value defined at the moment you execute bind(). That i is independent from the original i, and retains the value you have given it via bind().
that is because your "i" variable is not captured in the function passed as an argument to setInverval.
Therefore , when this function is invoked, i is always equal to clusters.length.
consider the differences between the two following pieces of code:
var arr = [1, 2, 3];
var broken = function() {
for(var i = 0; i < arr.length; ++i) {
setInterval(function() {
console.log("broken: " + arr[i]);
}, 1000);
// logs broken: undefined
}
};
var fixed = function() {
for(var i = 0; i < arr.length; ++i) {
setInterval((function(k) {
return function() {
console.log("fixed: " + arr[k]);
}
}(i)), 1000); // i is captured here
}
};

How do I execute a function after the callbacks inside a for loop are completed?

I have a for loop in a search function, with a function that does a callback inside the loop, and I want to execute a BUILD() function after the loop, and after all the callbacks are completed. I am not sure how to do that, because the loop finishes before all the callbacks are done. The callbacks are API requests to get me data, and I want to BUILD() with that data.
I read up on deferred, so I tried to put the for loop inside a function to the deferred, and then calling BUILD() on '.then( ... )'. But that doesn't seem to work - I think I am understanding it wrong.
HELP?!
Note, this is using the Google Maps Places API (search and getDetails).
var types = {
'gym' : 'fitness, gym',
'grocery_or_supermarket': ''
}
function search() {
for (var key in types) {
var request = { ... };
service.search(request, searchCallback);
}
// PROBLEM AREA
BUILD();
}
function searchCallback(results, status) {
for (var i = 0; i < results.length; i++) {
var request = { ... };
service.getDetails(request, detailsCallback);
}
}
function detailsCallback(place, status) {
// add place marker to maps and assign info window and info window event
}
With a small modification of your code, it can be achieved.
var total = 1337; // Some number
var internal_counter = 0;
var fn_callback = function() {
searchCallback.apply(this, arguments);
if (++internal_counter === total) {
BUILD();
}
};
for (var i=0; i<total; i++) {
service.search(request, fn_callback);
...
Explanation
First, we create a local function and variable.
The variable is a counter, which is increased when the callback is called.
The function is passed to the asynchronous method (service.search), which calls the original callback. After increasing the counter, check the value of the counter against the variable which holds the total number of iterations. If these are equal, call the finishing function (BUILD).
A complex case: Dealing with nested callbacks.
var types = { '...' : ' ... ' };
function search() {
var keys = Object.keys(types);
var total = keys.length;
// This counter keeps track of the number of completely finished callbacks
// (search_callback has run AND all of its details_callbacks has run)
var internal_counter = 0;
for (var i=0; i<total; i++) {
var request = { '...' : ' ... ' };
services.search(request, fn_searchCallback);
}
// LOCAL Function declaration (which references `internal_counter`)
function fn_searchCallback(results, status) {
// Create a local counter for the callbacks
// I'm showing another way of using a counter: The opposite way
// Instead of counting the # of finished callbacks, count the number
// of *pending* processes. When this counter reaches zero, we're done.
var local_counter = results.length;
for (var i=0; i<results.length; i++) {
service.getDetails(request, fn_detailsCallback);
}
// Another LOCAL function (which references `local_counter`)
function fn_detailsCallback(result, status) {
// Run the function logic of detailsCallback (from the question)
// " ... add place marker to maps and assign info window ... "
// Reduce the counter of pending detailsCallback calls.
// If it's zero, all detailsCallbacks has run.
if (--local_counter === 0) {
// Increase the "completely finished" counter
// and check if we're finished.
if (++internal_counter === total) {
BUILD();
}
}
} // end of fn_detailsCallback
} // end of fn_searchCallback
}
The function logic is explained in the comments. I prefixed the heading of this section with "Complex", because the function makes use of nested local functions and variables. A visual explanation:
var types, BUILD;
function search
var keys, total, internal_counter, fn_searchCallback;
function fn_searchCallback
var result, status; // Declared in the formal arguments
var local_counter, i, fn_detailsCallback;
function fn_detailsCallback
var result, status; // Declared in the formal arguments
In the previous picture, each indention level means a new scope Explanaation on MDN.
When a function is called, say, 42 times, then 42 new local scopes are created, which share the same parent scope. Within a scope, declared variables are not visible to the parent scope. Though variables in the parent scope can be read and updated by variables in the "child" scope, provided that you don't declare a variable with the same name. This feature is used in my answer's function.
I think you understand this already, but as it is the BUILD() is getting called linearly while the previous callback functions are still running. It's like you've created extra threads. One way to solve the problem would be to make BUILD a callback from the search function with the for loop in it. This would guarantee all functionality is complete before calling it.
This question might help implement the callback: Create a custom callback in JavaScript

Defining anonymous functions in a loop including the looping variable?

I know that this code doesn't work and I also know why.
However, I do not know how to fix it:
JavaScript:
var $ = function(id) { return document.getElementById(id); };
document.addEventListener('DOMContentLoaded', function()
{
for(var i = 1; i <= 3; i++)
{
$('a' + i).addEventListener('click', function()
{
console.log(i);
});
}
});
HTML:
1
2
3
I want it to print the number of the link you clicked, not just "4".
I will prefer to avoid using the attributes of the node (id or content), but rather fix the loop.
Wrap the loop block in its own anonymous function:
document.addEventListener('DOMContentLoaded', function()
{
for(var i = 1; i <= 3; i++)
{
(function(i) {
$('a' + i).addEventListener('click', function() {
console.log(i);
})
})(i);
}
}
This creates a new instance of i that's local to the inner function on each invocation/iteration. Without this local copy, each function passed to addEventListener (on each iteration) closes over a reference to the same variable, whose value is equal to 4 by the time any of those callbacks execute.
The problem is that the inner function is creating a closure over i. This means, essentially, that the function isn't just remembering the value of i when you set the handler, but rather the variable i itself; it's keeping a live reference to i.
You have to break the closure by passing i to a function, since that will cause a copy of i to be made.
A common way to do this is with an anonymous function that gets immediately executed.
for(var i = 1; i <= 3; i++)
{
$('a' + i).addEventListener('click', (function(localI)
{
return function() { console.log(localI); };
})(i);
}
Since you're already using jQuery, I'll mention that jQuery provides a data function that can be used to simplify code like this:
for(var i = 1; i <= 3; i++)
{
$('a' + i).data("i", i).click(function()
{
console.log($(this).data("i"));
});
}
Here, instead of breaking the closure by passing i to an anonymous function, you're breaking it by passing i into jQuery's data function.
The closure captures a reference to the variable, not a copy, which is why they all result in the last value of the 'i'.
If you want to capture a copy then you will need to wrap it in yet another function.

Variable Undefined in Anonymous Function

function updateServerList() {
var i;
for (i=0; i < servers.length; i++) {
var server = servers[i];
var ip = server['serverIp']
var html = constructServer(i);
var divId = '#server' + ip.replace(new RegExp("\\.", "mg"), "-");
var visible = $(divId).find(".server_body").is(":visible");
var div = $(divId);
div.html(html);
// Set div class.
var prevState = div.attr('class').substring(7)
if (prevState != server['state']) {
if (server['state'] == 'ok') {
console.debug(server);
div.slideUp('fast', function(server) {
$(this).removeClass();
$(this).addClass('server_ok');
var id = ipToId[server['serverIp']];
console.debug(id);
if (id == 0) {
adjacentIp = servers[1]['serverIp'];
adjacentDivId = '#server' + adjacentIp.replace(new RegExp('\\.', 'g'), '-');
$(adjacentDivId).before(this);
}
}).delay(1000);
div.slideDown();
}
}
}
console.debug shows server as being defined, but inside the anonymous function, server is not defined. What am I going wrong?
because server is an argument to the function, its masking the value of the server at the higher level. You need to either pass server to the function, or remove the function argument. I would do the latter, as slideUp doesn't give you a way to pass arguments. You could do it but its needlessly complicated; it would look something like the following
div.slideUp('fast', (function(server) {
return function(){
// your stuff here, server is now 'closed in', i.e. in a closure
}
})(server)); // <-- this server is the current value in the loop
what you are doing here is invoking a new function right away, passing in the argument server, and returning a new function that receives that value.
var server = servers[i];
var prevState = div.attr('class').substring(7);
if (prevState != server['state']) {
if (server['state'] == 'ok') {
console.debug(server);
div.slideUp('fast', function() {
...
var id = ipToId[server['serverIp']];
}
}
Inside your anonymous function, "server" is still within the function scope. No need to pass it in as an argument.
The Quick Fix
// ...
div.slideUp('fast', function() { // `server` argument removed
// ...
});
The Explanation
There is no need to pass server to the function. The anonymous function "closes" over the server variable.
This is merely a function declaration:
function (server) {...}
You aren't passing anything to the function yet, as it isn't being invoked yet! The (server) bit
in a function declaration simply lets you name the arguments to your function. Only when you invoke the function can you pass arguments:
var name = "Jill";
var showName = function (name) {
alert(name);
};
showName("Jack"); // alert box shows "Jack"
showName(); // alert box shows "undefined"
So, when you declare that the name of the first argument to your anonymous function is server, there is a name conflict which prevents the original from being accessible; the server in your anonymous function is whatever slideUp passes as the first argument, which, according to the documentation, is nothing, so server is now undefined.
If this is confusing (and I suspect it is), I would suggest reading about javascript closures. Here's a good place to get started.
Fun fact: you can actually access arguments, in order, without having any explicit names, by using Javascript's built in arguments array object inside a function:
var sum = function () {
var i, total = 0;
for(i = 0; i < arguments.length; ++i) {
total = total + arguments[i];
}
return total ;
};
alert(sum(1,2,3)); // Displays "6"
alert(sum(1,2,3,4)); // Displays "10"
alert(sum(1,0,2,3)); // Displays "6"
alert(sum()); // Displays "0"

Categories