Reputation: 17040
I am new to require.js and I need little guidance here.
/*
* 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"
I probably could define init.js, but say I want to keep that idea behind, how do I define a function called init
inside this main.js file and use it as my entry-point which calls functions in remote.js
??
Also, do I have to repeat define/require(['jquery', 'remote'].....
the dependency array again when I define my function?
Thanks
Upvotes: 0
Views: 444
Reputation: 1317
You have so many options to do this, but all chooses will require that you use define inside remote.js.
You could use name-value pair, and have some problems when you need to use remoteF2 inside remoteF1:
define(["jquery"], function($) {
return {
remoteF1: function() {
console.log("remoteF1 is called.");
},
remoteF2: function() {
console.log("remoteF2 is called.");
}
}
});
Now you can do this in your 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();
});
Or you could return a js object:
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.");
};
}
});
When you use remote.js you must declare using new remote();
should you choose the second method.
You need to set jquery dependency, because you don't know who will use you remote.js.
Upvotes: 1