【问题标题】:Higher order functions not working in casperjs高阶函数在 casperjs 中不起作用
【发布时间】:2014-12-10 18:34:36
【问题描述】:

我有这样定义的函数

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)中尝试,相同的代码可以正常工作。我做错了什么?

【问题讨论】:

    标签: coffeescript phantomjs casperjs


    【解决方案1】:

    它们当然可以工作,但不是在page context 的边界:

    注意:评估函数的参数和返回值必须是简单的原始对象。经验法则:如果可以通过 JSON 序列化就可以了。

    闭包、函数、DOM 节点等将起作用!

    谢天谢地,Functions 上有 toString 功能。因此,您可以稍微更改代码以将函数作为字符串传递并在页面上下文中传递evaling。

    (未测试)示例:

    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'
    

    【讨论】:

    • 非常感谢。它没有开箱即用,但我明白了。我可以让它工作如下所示
    【解决方案2】:

    基于@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'
    

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      • 2022-07-15
      • 2016-05-07
      相关资源
      最近更新 更多