this.evaluate with function parameters for a large reusable function

时间:2016-07-11 21:15:50

标签: javascript function phantomjs casperjs

I'm using this.evaluate this way:

myData = this.evaluate(getData);

I need to pass two variables to the getData function, but unfortunately that doesn't work like this:

myData = this.evaluate(getData(varA,varB));

I don't want to call the function like this, as getData is a large function and I need to evaluate this function more often in the script:

myData = this.evaluate(function getData(varA,varB) {
// my code...
});

So what can I do instead to pass the parameters and still be able to call the function in other parts of the script?

1 个答案:

答案 0 :(得分:1)

你可以通过这种方式实现这一目标:

var casper = require('casper').create();

function add(a, b) {
    return a + b;
}

var result1, result2;
casper.start().then(function () {
     result1 = casper.evaluate(add, 3, 5);
     result2 = casper.evaluate(add, "Hello", ", World.");
}).then(function () {
    casper.echo('result1: ' + result1);
    casper.echo('result2: ' + result2);
})

casper.run();

输出:

result1: 8
result2: Hello, World.