我不仅对JavaScript比较陌生,而且对RequireJS(来自字符串C#背景)也比较陌生。当前在我的网页上,我有许多JavaScript函数。每个都有两个参数。想象一下,它们看起来像这样:
functionA(x1, y1) { ... }
functionB(x2, y2) { ... }
functionC(x3, y3) { ... }
当前,这些函数存在于我的HTML页面上的标记中,我只需要根据需要调用它们。
我的函数依赖于KnockoutJS,jQuery和其他一些JS库。我目前有Script标签,可以同步加载这些外部.js依赖项。但是我想使用RequireJS以便根据需要异步加载它们。为此,我计划将上述所有三个功能移动到名为MyFunctions.js的外部.js文件(一种AMD“模块”类型)中。该文件将有一个define()调用(对RequireJS的define函数),如下所示:
define(["knockout", "jquery", ...], function("ko","jquery", ...) {???} );
我的问题是如何“包装”我的functionA,functionB和functionC函数,其中??? 位于上方,因此我可以根据需要在页面上使用这些功能。例如,在HTML页面上按钮的onclick事件处理程序中,我想调用functionA并将两个参数传递给它;与functionB和functionC相同。
我不完全了解如何将这些函数包装在本身位于外部.js文件中的定义中。我知道,define可以确保在调用回调函数之前异步加载列出的库,但是这样做之后,我不了解网页的脚本标签将如何使用我的函数。我是否需要使用require来确保它们可用,例如:
require(["myfunctions"],function({not sure what to put here})]
我想我了解RequireJS的基础知识,但不了解如何包装我的函数,以便它们位于外部.js文件中,不会污染全局名称空间,但仍可以从主页上调用它,以便参数可以传递给他们。我想他们有很多方法可以做到这一点,但是在回顾RequireJS文档和其中的一些视频时,我不能说我了解如何...
感谢您的任何帮助。
只需让您的MyFunctions.js文件返回一个对象,您已经向该对象添加了要公开的方法,如下所示:
define([], function(){
function myPrivateFunction(){
console.log('in private function');
}
function myPublicFunction(){
console.log('in public function');
}
function myOtherPublicFunction(){
console.log('in the other public function');
}
return {
functionA: myPublicFunction,
functionB: myOtherPublicFunction
};
});
您为函数指定参数的名称MyFunctions
根本没有关系。名称字符串和相关性数组中字符串的顺序确实很重要,该函数的参数顺序也很重要,但参数的名称无关紧要。例如
require('myFunctions', 'knockout', 'jquery', function(myFunctions, ko, $){
//here we can use the myFunctions, ko and $ variables.
//To call the public function, use the name which the function was
//exposed as; functionA
myFunctions.functionA();
});
上面的示例代码与以下代码完全相同:
require('myFunctions', 'knockout', 'jquery', function(my, k, j){
//In this example, your functions will be on the value of the 'my' variable,
//knockout will be the value of the 'k' variable and jQuery will be the
//value of the 'j' variable.
//To call the public function, use the name which the function was
//exposed as; functionA
my.functionA();
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句