2016-10-12 45 views
0

这是关于main.js我猜,但我已经尝试了我在网上找到的所有例子,他们只是没有工作。如何在HTML中通过RequireJS调用已定义的函数?

我目前:三个模块(one.js,two.js,three.js所),main.js,index.html,然后一些参考文件,如require.js

one.js

define("one",['./two', './three'], function(two, three) { 
    var one = 1; 
    return { 
    value: function(e){ 
     return one; 
    } 
    } 
}); 

two.js

define("two",['./one', './three'], function(one, three) { 
    var two = 2; 
    return { 
    value: function(){ 
     return two; 
    } 
    }  
}); 

main.js

require(["one", "two", "three"], function (one, two, three) { 

}); 

我的HTML:

<html> 
    <head> 
     <title>My App</title> 
     <script data-main="scripts/main" src="scripts/require.js"></script> 
    </head> 
    // the function from two.js having the same name as another in one.js needs to be called here. 
    <body onload="value();"> 
     <h1>My App</h1> 
    </body> 
</html> 

回答

0

调用onload功能是相同的概念在main.jsrequire回调invocking。你只需要调用require内部功能的回调:

require(["one", "two", "three"], function (one, two, three) { 
    one.value(); 
}); 

所有require的回调参数是由define创建函数的引用。在它们内部的相同方法之间不会有任何冲突。

0

你不能这样做你试图做到这一点。你的电话:

require(["one", "two", "three"], function (one, two, three) { }); 

会加载你的模块,但是它们的值可以通过你的回调参数获得。 什么都不会输出到全球空间。<body onload="value();">的工作,value必须在全球空间。

另一个问题是RequireJS是异步的。因此,即使您重写了代码,故意让模块two将其value泄漏到全局空间,但代码无法可靠运行。一般而言,您无法知道您的require电话何时会完成,相对于bodyonload将被解雇。

你可以通过让“胶水代码”加载你需要的东西来解决这个问题。设置<body onload="onBodyLoaded()">,并有script之前body有:

function onBodyLoaded() { 
    require(["two"], function (two) { 
     two.value(); 
    }); 
} 

如果这是我的代码,我其实不使用onload属性,而是会拥有script体后的东西,如:

(function() { 
    document.body.addEventListener("load", function onBodyLoaded() { 
     require(["two"], function (two) { 
      two.value(); 
     }); 
    }); 
}()); 

或者我会用domReady plugin。与听body上的load事件不太一样,但它可能“足够好”。

相关问题