I have some javascript code that I am calling in casperJS, its quite short so I have included the whole listing
var links = [];
var casper = require('casper').create();
function getLinks() {
var links = document.querySelectorAll('table');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('id');
});
}
casper.start('example.html', function() {
links = this.evaluate(getLinks);
});
casper.run(function() {
this.echo(links.length + ' links found:');
this.echo(' - ' + links.join('\n - ')).exit();
});
This outputs the expected
3 links found:
- table A
- table B
- table C
Whereas switching to breaking out the anonymous function in getLinks so that getLinks is replaced with the below two functions
function extract(e) {
return e.getAttribute('id');
}
function getLinks() {
var links = document.querySelectorAll('table');
return Array.prototype.map.call(links, extract);
}
Yields
TypeError: 'null' is not an object (evaluating 'links.length')
/Users/jrrpl/git/gamecock/download.js:18
/usr/local/Cellar/casperjs/1.1-beta3/libexec/modules/casper.js:408 in checkStep
UPDATE
It seems that the reference to the named function causes casper.run() to execute early. Anyone know why this would occur?
linksis defined.extractfunction to compare what's going on? Inspecting some values ofein both places could be very informative.querySelectorAllwill never returnnull, nor willArray.prototype.map, so I think we're missing something. Is this a complete example, or did you change something to make it shorter?