brainCloud supports share script now, which means you can include another script in a different script by simply using the new bridge.include(“scriptname.ccjs”)
operation.
The following rules apply:
A script can import multiple scripts (of course!)
The scripts must all be present within the app… (i.e. no including scripts from other apps)
bridge.include()
calls must come first in a script. The only lines allowed to be before bridge.include() are blank lines,//
comments, and/or the”use strict”;
directiveThe extension is ignored by the call – but we recommend you append
.ccjs
anyway ← this may be helpful in the future (we have plans!)The includes are processed when the script is first loaded into the server (and cached, brainCloud algorithms will check to ensures that a script is not included multiple times) - so include operations do not happen at runtime each run - so it's faster
But that does mean they use more memory - so try to keep things small if possible - best for everyone (and less chance that we would have to unload the script to save memory)
For instance: you have one script called MathFunctions
as below:
function sumNums( num1, num2 ) {
return (num1 + num2);
}
function prodNums( num1, num2 ) {
return (num1 * num2 );
}
You can include it to another cloud code script as below:
"use strict";
bridge.include("MathFunctions.ccjs");
function main() {
var response = {};
response.answersum = sumNums(data.number1, data.number2);
response.answerprod = prodNums(data.number1, data.number2);
return response;
}
main();
You may already know, brainCloud uses the Rhino JavaScript engine as cloud code scripts editor. The current version of Rhino does not support the ES6 "class" syntax yet, though it can import some Java system lib classes by calling importClass()
operation, which is totally different than bridge.include()
operation.
---
An example of using importClass()
operation in cloud code script:
importClass(java.util.ArrayList);
var list = new ArrayList();
list.add("one");
list.add("two");
---
---
An example of using function closure to sort out properties and methods:
Car.ccjs
script:
var Car = (function () {
function Car(){
}
Car.Init = function (brand, speed){
Car.Name = brand;
Car.Speed = speed;
}
Car.Distance = function(time){
return Car.Speed*time;
}
return Car;
})();
Then include the above function to another cloud code script as below:
"use strict";
bridge.include("Car.ccjs");
function main() {
var response = {};
Car.Init("Hyndai",100);
response.distance = Car.Distance(3);
return response;
}
main();
---