高阶函数在casperjs中不起作用

时间:2014-12-10 18:34:37

标签: coffeescript phantomjs casperjs

我有像这样定义的功能

casper.executeRemote = (fn,params)->
    ->
        try
            fn.apply(this,params)
        catch e
            console.log(e)

getLinks = ->
    elems = document.querySelectorAll('#pagination-flickr a')

我正在调用下面的函数

casper.then ->
    all_links = @evaluate @executeRemote getLinks
    casper.log all_links,'debug'

但是当我尝试在casperjs

中运行时,我收到以下错误
ReferenceError: Can't find variable: fn

如果我在浏览器控制台(编译的js)中尝试,相同的代码工作正常。我做错了什么?

2 个答案:

答案 0 :(得分:2)

当然他们有效,但不在page context的边界:

  

注意: evaluate函数的参数和返回值必须是一个简单的原始对象。经验法则:如果它可以通过JSON序列化,那就没关系了。

     

闭包,函数,DOM节点等将工作!

值得庆幸的是toString上有Function个功能。因此,您可以稍微更改代码,以便将函数作为字符串传递,并在页面上下文中eval

(未经测试)示例:

casper.executeRemote = (fn,params)->
    fn = eval('('+fn+')')
    try
        fn.apply(this,params)
    catch e
        console.log(e)

getLinks = ->
    elems = document.querySelectorAll('#pagination-flickr a')

casper.then ->
    all_links = @evaluate(@executeRemote, getLinks.toString())
    casper.log all_links,'debug'

答案 1 :(得分:1)

基于@ Artjom的回答。我修改了如下所示的代码,然后就可以了

executeRemote = (fn,params)->
    ->
        try
            fn.apply(this,params)
        catch e
            console.log(e)

getLinks = ->
    elems = document.querySelectorAll('#pagination-flickr a')
    links = (link.href for link in elems)

remoteWrapper = (excRm,gL)->
        excRm=eval('('+excRm+')')
        gL=eval('('+gL+')')
        fn=excRm(gL)
        fn()

casper.on 'remote.message',(message)->
    @echo message

casper.then -> 
    all_links = @evaluate remoteWrapper, executeRemote.toString(), getLinks.toString()
    casper.log all_links,'debug'