Components All New MacOS Windows Linux iOS
Examples Mac & Win Server Client Guides Statistic FMM Blog Deprecated Old

JS.AddFunction

Adds a global function defined as a text string.

Component Version macOS Windows Linux Server iOS SDK
JavaScript 10.0 ✅ Yes ✅ Yes ✅ Yes ✅ Yes ✅ Yes
MBS( "JS.AddFunction"; JSRef; Name; JavaScript )   More

Parameters

Parameter Description Example
JSRef The JavaScript reference number. $js
Name The name of the function. "test"
JavaScript The JavaScript code. "function (x,y) { return x+y; }"

Result

Returns OK or error.

Description

Adds a global function defined as a text string.
Optional provide a file name to show in stack traces.
Function source code may contain a function name, but we use only the name parameter to register the function as global one.

Examples

Define a function and call it:

Set Variable [ $js ; Value: MBS( "JS.New" ) ]
Set Variable [ $r ; Value: MBS( "JS.AddFunction"; $js; "adder"; "function (x,y) { return x+y; }" ) ]
Show Custom Dialog [ "Result" ; MBS( "JS.CallFunction"; $JS; "adder"; 3; 4 ) ]
Set Variable [ $r ; Value: MBS( "JS.Release"; $JS ) ]

Initialize JavaScript environment with two functions:

If [ Length($$js) = 0 ]
    Set Variable [ $$js ; Value: MBS( "JS.New" ) ]
    Set Variable [ $r ; Value: MBS( "JS.AddFunction"; $$js; "makeCRCTable"; "function makeCRCTable(){
                var c;
                var crcTable = [];
                for(var n =0; n < 256; n++){
                                c = n;
                                for(var k =0; k < 8; k++){
                                                c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
                                }
                                crcTable[n] = c;
                }
                return crcTable;
}") ]
    Set Variable [ $r ; Value: MBS( "JS.AddFunction"; $$js; "crc32"; "function crc32(str) {
                var crcTable = crcTable || (crcTable = makeCRCTable());
                var crc = 0 ^ (-1);

                for (var i = 0; i < str.length; i++ ) {
                                crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
                }

                return (crc ^ (-1)) >>> 0;
}") ]
End If

Register custom function for "js" JavaScript environment:

# Register one function. Replacing older one with same name
Set Variable [ $r ; Value: MBS( "JS.AddFunction"; "js"; JavaScriptCustomFunctions::Name; "function(" & Substitute(List ( JavaScriptCustomFunctionParameters::Name ); ¶; ", ") & ") { " & JavaScriptCustomFunctions::Body & " }" ) ]
If [ MBS("IsError") ]
    Show Custom Dialog [ "Failed to add function." ; $r ]
End If

See also

Example Databases

Blog Entries

This function checks for a license.

Created 7th December 2019, last changed 5th June 2021


JS.AddFileMakerSQLFunction - JS.CF