我是require.js的新手,我在这里几乎不需要任何指导。
/*
* This app depends on jquery and a remote script called "remote.js" (serve over localhost :p)
* Locally I will have main.js and require.js.
* main.js contain an entry function "init" and it depends on jquery
* and remote.js to be fully loaded.
*/
require.config({
paths: {
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min",
"remote": "http://localhost:8000/scripts/remote"
},
shim: {
"init": {
deps: ["jquery", "remote"]
}
},
urlArgs: "bust=" + (new Date()).getTime()
});
define(["jquery", "remote"], function($, remote) {
console.log("just entered the outerscope of the init function.");
console.log(remote);
return {
init: function() {
console.log("entered init function");
}
}
});
/* the following is in remote.js*/
function remoteF1() {
console.log("remote function 1 is called.");
};
function remoteF2() {
console.log("remote function 2 is called.");
};
// and I thought about wrapping them around with "define" or "require"
我可能会定义init.js,但是我想保留这个想法,如何在这个main.js文件中定义一个名为init
的函数并将其用作我的入口点它调用remote.js
??
另外,在定义函数时,是否必须再次重复define/require(['jquery', 'remote'].....
依赖关系数组?
感谢
答案 0 :(得分:1)
你有很多选择可以做到这一点,但所有选择都要求你在remote.js中使用define。
你可以使用名称 - 值对,当你需要在remoteF1中使用remoteF2时会遇到一些问题:
define(["jquery"], function($) {
return {
remoteF1: function() {
console.log("remoteF1 is called.");
},
remoteF2: function() {
console.log("remoteF2 is called.");
}
}
});
现在你可以在main.js中执行此操作:
define(["jquery", "remote"], function($, remote) {
console.log("just entered the outerscope of the init function.");
console.log(remote);
var remote = new remote();
remote.remoteF1();
});
或者你可以返回一个js对象:
define(["jquery"],function($){
return function(){
var privateFunction = function(){};
this.remoteF1 = function () {
privateFunction();
console.log("remote function 1 is called.");
};
this.remoteF2 = function () {
console.log("remote function 2 is called.");
};
}
});
当您使用remote.js时,如果您选择第二种方法,则必须使用new remote();
声明。
您需要设置jquery依赖项,因为您不知道谁将使用您的remote.js。