【问题标题】:how to execute external function in dalekjs .execute( )?如何在 dalekjs .execute() 中执行外部函数?
【发布时间】:2014-02-24 09:58:04
【问题描述】:

我想在 dalekjs 的 .execute() 函数中执行一个外部函数。 有可能吗?

【问题讨论】:

    标签: javascript dalekjs


    【解决方案1】:

    取决于您对external 的含义。

    如果您要执行客户端 JavaScript 中已经存在的函数,则必须可以通过全局 window 对象访问它。例如:

    在我的一个客户端脚本中,我有这样的内容:

    function myAwesomeFn (message) {
      $('body').append('<p>' + message + '</p>');
    }
    

    如果该函数是在全局范围内定义的(不在某些 IIFE f.e. 内),您可以在执行函数中触发它,如下所示:

    test.execute(function () {
      window.myAwesomeFn('Some message');
    });
    

    如果您的意思是“在 Dalek 测试套件中定义的函数”与外部,我可能会让您失望,因为 Daleks 测试文件和 execute 函数的内容是在不同的上下文中调用的(甚至是不同的 JavaScript 引擎)。

    所以这不起作用:

    'My test': function (test) {
       var myFn = function () { // does something };
    
       test.execute(function () {
         myFn(); // Does not work, 'myFn' is defined in the Node env, this functions runs in the browser env
    
       })
     }
    

    有什么作用:

    'My test': function (test) {
    
    
       test.execute(function () {
         var myFn = function () { // does something };
         myFn(); // Does work, myFn is defined in the correct scope
    
       })
     }
    

    希望能回答您的问题,如果没有,请提供更多详细信息。

    编辑:

    使用节点自己的 require 加载文件

    var helper = require('./helper');
    module.exports = {
      'My test': function (test) { 
         test.execute(helper.magicFn)
       }
     };
    

    在你的 helper.js 中,你可以做任何你想做的事, 这是有道理的(或多或少):

    module.exports = {
      magicFn: function () { 
         alert('I am a magic function, defined in node, executed in the browser!');
       }
     };
    

    有关如何保持测试代码 DRY 的更多策略;), 检查此回购/文件:Dalek DRY Example

    【讨论】:

    • 外部我的意思是如果我可以编写一个包含 javascript 函数的文件,并且我可以包含该文件并像任何其他 js 一样在 dalekjs 的 .execute() 中调用该函数。由于 dalek 是关于 javascript 的,所以也可以这样想吗?
    • 用一些关于文件包含的更多信息更新了答案。
    • 我希望这对我有用。您对 Dalekjs 的大力支持真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    相关资源
    最近更新 更多