BANano 6.59
BANano is a library created by Alain Bailleul that transpiles B4J source code to Javascript/HTML/css.
It can be used to make Websites and WebApps, even Progressive Web Apps (PWA).
It does not rely on any javascript/css framework, so you can use whatever one you prefer.
BANano
Events:
- AssetsLoaded (pathsNotFound() As String)
- CallAjaxResult (Success As Boolean, UniqueID As String, Result As String)
- CallInlinePHPResult (Success As Boolean, UniqueID As String, Result As String)
- EmailSent (Tag As String, Message As String)
- IsConnectedResult (Tag As String, Result As Boolean)
- OffLine()
- OnLine()
- ParseEvent (params As Map)
- Ready()
Fields:
- ASSETS_FOLDER As String
- Header As BANanoHeader
- HTML_NAME As String
- IsForBANanoServer As Boolean
- JAVASCRIPT_NAME As String
- MANIFEST_NAME As String
- PHP_NAME As String
- PHPHost As String
- SCRIPTS_FOLDER As String
- SERVICEWORKER_NAME As String
- STYLES_FOLDER As String
- TranspilerOptions As BANanoTranspilerOptions
- UploadHandlerPath As String
- Version As String
- Version659 As String
- VersionName As String
Functions:
- Alert (text As String)
Shows an alert box, same as BANano.Msgbox
- AssetsIsDefined (bundleName As String) As Boolean
Check if bundle has already been defined
- AssetsLoad (bundleName As String, assets As List) As BANanoPromise
Loads a bundle of assets and returns a promise.
If the asset is a CSS or JS file, it must have been Added with the BANano.header.Add...ForLater() methods
' in Sub AppStart()
BANano.Header.AddCSSFileForLater("mini-nord.min.css")
...
' in Sub BANano_Ready()
Dim pathsNotFound() as String
If BANano.AssetsIsDefined("Loader") = False then
Dim prom as BANanoPromise = BANano.AssetsLoad("Loader", Array("./assets/1.jpg", "./styles/mini-nord.min.css"))
prom.Then(Null)
Log("Loader has been loaded!")
prom.Else(pathsNotFound)
Log("Doh! Loader has not been loaded completely!")
For Each path As String In pathsNotFound
Log(path)
Next
prom.End
End if
- AssetsLoadEvent (module As Object, bundleAndEventName As String, assets As List)
Loads a bundle of assets and uses the BANano bundleEventName_AssetsLoaded() event
If the asset is a CSS or JS file, it must have been Added with the BANano.header.Add...ForLater() methods
The bundle name and eventName is the same.
' in Sub AppStart()
BANano.Header.AddCSSFileForLater("mini-nord.min.css")
...
' in Sub BANano_Ready()
BANano.AssetsLoadEvent(Me, "Loader", Array("./assets/1.jpg", "./styles/mini-nord.min.css"))
...
Sub loader_AssetsLoaded(pathsNotFound() As String)
If BANano.IsNull(pathsNotFound) = False Then
Log("Doh! Loader has not been loaded completely!")
For Each path As String In pathsNotFound
Log(path)
Next
Else
Log("Loader has been loaded!")
End If
End Sub
- AssetsLoadWait (bundleName As String, assets As List) As Object
Loads a bundle of assets and waits until it is loaded. Returns a String array containing the paths that failed.
If the asset is a CSS or JS file, it must have been Added with the BANano.header.Add...ForLater() methods
Note: Do not use a BANano.AWait around this method as it already does it internally and needs some other settings before being able to run.
' in Sub AppStart()
BANano.Header.AddCSSFileForLater("mini-nord.min.css")
...
' in Sub BANano_Ready()
Dim pathsNotFound() as String
If BANano.AssetsIsDefined("Loader") = False then
pathsNotFound = BANano.AssetsLoadWait("Loader", Array("./assets/1.jpg", "./styles/mini-nord.min.css"))
If BANano.IsNull(pathsNotFound) = False Then
Log("Doh! Loader has not been loaded completely!")
For Each path As String In pathsNotFound
Log(path)
Next
Else
Log("Loader has been loaded!")
End If
end if
- AssetsReset
Reset the dependency trackers
- Await (promise As Object) As Object
- B4JCallSubX (Component As Object, Sub As String, Arguments As Object()) As Object
Similar to CallSub, but with unlimited arguments. Arguments must be passed as an Array.
Can only be used in pure B4J, not in a BANano module!
- B4JRemoveMeFromCache (cachedPages As Map, pageID As String)
Removes a page from the BANanoServer cache. See the BANanoServer.b4xlib: BANanoServer class.
- B4JScavengeCache (cachedPages As Map)
Runs the Cache Scavenger. See the BANanoServer.b4xlib: BANanoCacheScavenger class.
- B4JUpdateFromCache (me As B4AClass, cachedPages As Map, ws As WebSocket, ba As BA) As BANanoCacheReport
Add or Update a SERVERPage to the BANanoServer cache.
- BN (B4JName As String) As String
Returns the full banano name that will be used in the Transpiled javascript
B4JName MUST be a quoted srting:
Will work:
log(BANano.BN("myvar")
' returns e.g. _banano_mylib_myvar
Will not work:
dim tmp as String = "myvar"
log(BANano.BN(tmp)
- BP
BreakPoint.
Stops the execution of JavaScript. Is ignored if in release mode.
Use the Developer Tools in the browser to inspect e.g. variable values
- Build (outputDir As String)
Should be called in AppStart() in the Main module.
- BuildAsB4XLib (LibraryVersion As String)
Should be called in AppStart() in the Main module.
Will Build the transpiled files to your Additional Libraries folder as a B4XLib.
You do not need to compile your Library with the B4J IDE
- BuildAsB4XlibForABM (ABMStaticFilesFolder As String, LibraryVersion As String)
Should be called in AppStart() in the Main module.
Will Build the transpiled files to your Additional Libraries folder as a B4XLib for ABMaterial (prefix: ABMBanano).
You do not need to compile your Library with the B4J IDE
If ABMStaticFilesFolder (the /www folder) is set, then the assets will be automatically unzipped in this folder.
e.g. BANano.BuildAsB4XlibForABM("D:\MyProject\MyABMProject\Objects\www","1.15")
- BuildAsLibrary
Should be called in AppStart() in the Main module.
Will Build the transpiled files to your Additional Libraries folder.
Do not forget to compile your Library with the B4J IDE: Project - Compile To Library
to generate the .jar and .xml files.
- BuildForServer (outputDir As String)
Should be called in AppStart() in the Main module.
Builds all the css/html/javascript files from the B4J source code.
- CallAjax (url As String, type As String, dataType As String, data As Object, uniqueId As String, withCredentials As Boolean, headers As Map)
Makes an ajax call. Returns the result of the call to BANano_CallAjaxResult()
Example:
dim headers as Map
headers.initialize
headers.put("Content-Type", "application/json")
BANano.CallAjax("https://reqres.in/api/users?page=2","GET","jsonp", "","ID0001", false, headers)
Sub BANano_CallAjaxResult(Success As Boolean, UniqueID As String, Result As String)
Log(Success)
Log(UniqueID)
Log(Result)
End Sub
- CallAjaxWait (url As String, type As String, dataType As String, data As Object, withCredentials As Boolean, headers As Map) As Object
Makes an ajax call. Returns the result of the call
Note: Do not use a BANano.AWait around this method as it already does it internally and needs some other settings before being able to run.
- CallBack (module As Object, methodName As String, params As List) As Object
Useful where a library you are wrapping needs a function() {} as parameter.
- CallBackExtra (module As Object, methodName As String, params As List, extraParams As List) As Object
Useful where a library you are wrapping needs a function() {} as parameter.
The params are the 'event' params like in the normal CallBack.
The extraParams are extra parameters that the callback method takes, not default to the callback
Example:
Sub GetFileFromServer(FileName As String)
Dim Response As BANanoFetchResponse
Dim Blob As BANanoObject
' list (GET is default, and we do not need extra options so we pass Null for the options)
Dim fetch1 As BANanoFetch
fetch1.Initialize(FileName, Null)
fetch1.Then(Response)
' we got the response promise, so resolve it to a blob
fetch1.Return(Response.Blob)
fetch1.Then(Blob)
' we got the blob, read it in a FileReader
Dim FileReader As BANanoObject
FileReader.Initialize2("FileReader", Null)
Dim event As BANanoEvent
' the CallBackExtra, which next to the normal event, also we like to pass the filename
FileReader.SetField("onload", BANano.CallBackExtra(Me, "ReadData", Array(event), Array(FileName)))
' get the DataURL
FileReader.RunMethod("readAsDataURL", Blob)
fetch1.End ' always end a fetch with this!
End Sub
Sub ReadData(event As BANanoEvent, FileName As String) 'ignore
' get the data
Dim Target As BANanoObject = event.OtherField("target")
Dim DataUrl As String = Target.GetField("result").Result
Log(FileName)
log(DataURL)
End Sub
- CallBackMethod (module As Object, methodName As String) As Object
Get the BANano name of a method, to be used in e.g. AddEventListener and RemoveEventListener.
- CallDebugger
DEPRECIATED: Use BANano.BP instead.
Stops the execution of JavaScript. Is ignored if in release mode.
Use the Developer Tools in the browser to inspect e.g. variable values *
- CallInlinePHP (methodName As String, methodParams As Map, uniqueId As String)
Makes a php call to an inline php method. Returns the result of the call to BANano_CallInlinePHPResult()
Example:
BANano.CallInlinePHP("SayHello", CreateMap("Name": "BANano"), "ID0001")
#if PHP
function SayHello($Name) {
$ret = Array("answer" => "Hello " .$Name. "!");
echo json_encode($ret);
}
#End If
Sub BANano_CallInlinePHPResult(Success As Boolean, UniqueID As String, Result As String)
Log(Success)
Log(UniqueID)
Log(Result)
End Sub
- CallInlinePHPWait (methodName As String, methodParams As Map) As Object
Makes a php call to an inline php method. Returns the result of the call.
Note: Do not use a BANano.AWait around this method as it already does it internally and needs some other settings before being able to run.
Example:
Dim res as String = BANano.CallInlinePHPWait("SayHello", CreateMap("Name": "BANano"))
log(res)
#if PHP
function SayHello($Name) {
$ret = Array("answer" => "Hello " .$Name. "!");
echo json_encode($ret);
}
#End If
- CallSub (module As Object, methodName As String, params As List) As Object
Calls a method from another module/class
- CheckInternetConnection (tag As String)
Checks if the app can reach the internet
Will raise the banano IsConnected(Tag as String, Result as boolean) event
you can then use the tag to see who was the caller and act accordingly
- CheckInternetConnectionWait As Boolean
Checks if the app can reach the internet
Note: Do not use a BANano.AWait around this method as it already does it internally and needs some other settings before being able to run.
- Concat (arr As List, otherArray As List) As Object
The concat method creates a new array by merging (concatenating) existing arrays.
The concat method does not change the existing arrays. It always returns a new array.
- Console As BANanoConsole
Returns the Console Object as a BANanoConsole.
- CreateElement (Tag As String) As BANanoElement
Creates a BANanoElement, not attached to something
- CreateObjectUrl (object As Object) As BANanoURL
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter.
The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
To release an object URL, call revokeObjectURL().
- DebugTrackLine (moduleName As String, virtualLineNumber As Int)
DEPRECIATED: Use BANano.BP instead
When running in debug mode, you can get some extra debug information by tracking some line.
In the generated javascript file, some comment lines showing the the B4J code have a virtual number prefix: [number]
You can use this number to track the transpiling of that line.
Tracks in the B4J log
- DebugTrackMethod (moduleName As String, methodName As String)
DEPRECIATED: Use BANano.TM or BANano.TMC instead
Will track this method in the Browsers log
- DecodeURI (o As Object) As String
The decodeURI() function is used to decode a URI.
- DecodeURIComponent (o As Object) As String
The decodeURIComponent() function decodes a URI component.
- DeepClone (obj As Object) As Object
Deep Clones an object (e.g. a map)
- DeepMerge (obj1 As Object, obj2 As Object) As Object
Merges two object into one (e.g. two maps into one)
- DependsOnAsset (AssetFileNameOrURL As String)
ONLY works for Builds, using b4xlibs, not for .jar libs.
This should NOT be used in AppStart, but is mainly for a library where e.g. for a Custom View.
Should be placed in the Initialize method.
Assets defined with header.AddCSSFile, header.AddJavascriptFile or other assets (images, fonts) are ONLY loaded
if the class where the DependsOnAsset is defined, is actually used in the final app.
NOTE: AssetFileNameOrUrl MUST be a String, NOT a variable! (case sensitive)
- EmptyLocalStorage (key As String)
Empty the LocalStorage for this domain
- EmptySessionStorage (key As String)
Empty the SessionStorage for this domain
- EncodeURI (o As Object) As String
The encodeURI() function is used to encode a URI.
- EncodeURIComponent (o As Object) As String
The encodeURIComponent() function encodes a URI component.
- Eval (o As Object) As Object
The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
- Every (arr As List, callbackMethod As String) As Object
The every method checks if all array values pass a test.
callbackMethod should look as: Sub MyCallback(value as Object, index as int, array as List)
- Exists (target As String) As Boolean
Checks if a element(s) exists
Target: and ID (use #), class (use ."), tag etc...
- Existy (var As Object) As Boolean
Test if the object is existy (not null or undefined)
- ExternalHTMLToHTMLBlocks (name As String, fullPath As String)
Can only be used in AppStart()
Will extract all html blocks where the tag has the class BANANO
if the class = BANANO, then the body HTML String will not contain these elements.
you can later get their HTML by using the GetHTMLBlock() method.
the Body HTML can be returned with the GetHTMLBody() method.
- Filter (arr As List, callbackMethod As String) As Object
The filter method creates a new array with array elements that passes a test.
callbackMethod should look as: Sub MyCallback(value as Object, index as int, array as List)
- Finally
A try catch in B4J does not have a Finally statement.
e.g.
Dim num As Int = 10
Dim divider As Int = 0
Try
If divider = 0 Then
BANano.Throw("You can not divide by 0!")
Else
Log(num/divider)
End If
Catch
Log(LastException)
' will still do the Finally part, but not the "After the Try" log.
Return
BANano.Finally 'ignore
Log("Always doing this")
End Try
Log("After the Try")
- Find (arr As List, callbackMethod As String) As Object
The find method returns the value of the first array element that passes a test function.
callbackMethod should look as: Sub MyCallback(value as Object, index as int, array as List)
- FindIndex (arr As List, callbackMethod As String) As Int
The findIndex method returns the index of the first array element that passes a test function.
callbackMethod should look as: Sub MyCallback(value as Object, index as int, array as List)
- ForEach (arr As List, callbackMethod As String)
The forEach method calls a function (a callback function) once for each array element.
callbackMethod should look as: Sub MyCallback(value as Object, index as int, array as List)
- FromBase64 (s As String) As String
Converts a base 64 string back to a normal string
- FromJson (object As Object) As Object
Shortcut function to make an object of JSON
- GenerateUUID As String
Generates a UUID. Works both in B4J as in BANano code
- GeoLocation As BANanoGeoLocation
Returns the Navigator GeoLocation Object as a BANanoGeoLocation.
- GetAllViewsFromLayoutArray (module As Object, layoutName As String, unqiueIndex As Long) As Map
Returns a map with all the custom views that are in the layout, with unique index
The unique index was returned by the LoadLayoutArray() method.
All keys in the map are lowercased!
- GetAsset (url As String) As Object
returns the object previously loaded with AssetsLoad/AssetsLoadEvent/AssetsLoadWait
needs the exact url path used in the Load methods.
- GetCookie (name As String) As String
Returns a the value of the cookie
- GetCurrentUrl As String
Returns the full URL of the current page
- GetElement (target As String) As BANanoElement
Target: and ID (use #), class (use ."), tag etc...
- GetElements (target As String) As BANanoElement()
Target: and ID (use #), class (use ."), tag etc...
- GetFileAsArrayBuffer (fileURL As String, options As BANanoFetchOptions) As BANanoPromise
Does a Fetch with a resource (e.g. url) and an optional Request options object
Pass null if no request options need to be set
Returns a promise holding the ArrayBuffer
- GetFileAsDataURL (fileURL As String, options As BANanoFetchOptions) As BANanoPromise
Does a Fetch with a resource (e.g. url) and an optional Request options object
Pass null if no request options need to be set
Returns a promise holding the DataURL
Dim dataUrl As String
Dim dataUrlProm As BANanoPromise = BANano.GetFileAsDataURL("./assets/B4X.jpg", Null)
dataUrlProm.Then(dataUrl)
Log(dataUrl)
dataUrlProm.end
- GetFileAsJSON (fileURL As String, options As BANanoFetchOptions) As BANanoPromise
Does a Fetch with a resource (e.g. url) and an optional Request options object
Pass null if no request options need to be set
Returns a promise holding the JSON
- GetFileAsText (fileURL As String, options As BANanoFetchOptions, encoding As String) As BANanoPromise
Does a Fetch with a resource (e.g. url) and an optional Request options object
Pass null if no request options need to be set
Returns a promise holding the text
- GetHTMLBlock (name As String, origId As String, idPostFix As String) As String
Returns the HTML String from a removed HTML Block (using the BANANO class)
previously added with the ExternalHTMLToHTMLBlocks() method.
The idPostFix will be added to the original Id as _idPostFix. Is normally a number.
- getHTMLBody (name As String) As String
returns the HTML String with all HTML Blocks having the BANano class removed.
- GetLocalStorage (key As String) As Object
Returns the saved json from the key in the LocalStorage
- GetP (Class As Object, propName As String) As Object
Method to get a property from any class
- GetPageHTML (B4JClassName As String) As String
BANanoServer only. Returns the generated page HTML in Release Mode where /Files folder does not exist.
- GetPageID As String
In case you are connected to a BANanoServer, you can here retrieve the Page ID.
This Page ID can then be used in the request to a B4J handler class to identify where the class came from. *
- GetSessionStorage (key As String) As Object
Returns the saved json from the key in the SessionStorage
- GetSuffixFromID (id As String) As Long
Extracts the last number from an id
e.g. if the id = mybutton_1 then 1 is returned
- GetType (var As Object) As Object
Will be depreciated in the future. Use the normal B4J GetType() instead!
to get the type of the object (same as BANano.TypeOf)
- GetURLParamDefault (url As String, key As String, Default As Object) As Object
Gets all the URL parameter. If it does not exists it returns the passed default value.
- GetURLParams (url As String) As Map
Gets all the URL parameters as a map.
- GetViewFromLayout (module As Object, id As String) As Object
Returns the Custom view from a layout loaded with LoadLayout
- GetViewFromLayoutArray (module As Object, layoutName As String, id As String, uniqueIndex As Long) As Object
Returns the Custom view from a layout loaded with LoadLayoutArray, with unique index
The unique index was returned by the LoadLayoutArray() method.
- GZipGeneratedWebsite (minSizeKB As Double)
DEPRECIATED: Use BANano.TranspilerOptions.GZipGeneratedWebsite instead
Will GZip your html/css/js/json files on compilation. Set a minimum filesize so small files are not compressed
This is ONLY useful if you use NGinx with gzip_static set to 'on'
- History As BANanoHistory
Returns the History Object as a BANanoHistory.
- IIf (condition As Object, returnTrue As Object, returnFalse As Object) As Object
Shortcut method to do an 'if then else'
e.g.
mRoot = BANano.IIf(Root = "/", "/", "/" & TrimSlashes(Root) & "/")
- Import (moduleName As String) As BANanoPromise
- ImportWait (moduleName As String) As BANanoObject
- IndexOf (arr As List, searchValue As Object) As Int
The indexOf method searches an array for an element value and returns its position.
Note: The first item has position 0, the second item has position 1, and so on.
- IndexOf2 (arr As List, searchValue As Object, start As Int) As Int
The indexOf2 method searches an array for an element value and returns its position.
Note: The first item has position 0, the second item has position 1, and so on.
start: Where to start the search. Negative values will start at the given position counting from the end, and search to the end.
- INFINITY As Object
transpiles as 'Infinity'
- Initialize (eventName As String, appShortName As String, appVersion As Long)
Do not uses spaces in the appShortName!
- Initialize2 (eventName As String, appShortName As String, appVersion As Long, B4JAdditionalLibrariesPath As String)
Do not uses spaces in the appShortName!
- IsArray (var As Object) As Boolean
Test if the object is an array
- IsBoolean (var As Object) As Boolean
Test if the object is a boolean
- IsCapitalized (var As String) As Boolean
Test if the string is capitalized
- IsClass (var As Object, className As String) As Boolean
Test if the given value is a certain B4J class
className must be a String, not a variable.
e.g. BANano.IsClass(myObj, "MyB4JClassName")
- IsDate (var As Object) As Boolean
Test if the object is a date
- IsDecimal (var As Object) As Boolean
Test if the given value is decimal
- IsDomNode (var As Object) As Boolean
Test if the object is a DOM Node
- IsEmpty (var As Object) As Boolean
Test if the object is a empty
- IsError (var As Object) As Boolean
Test if the object is an error
- IsFinite (o As Object) As Boolean
The isFinite() function determines whether a number is a finite, legal number.
- IsFunction (var As Object) As Boolean
Test if the object is a function
- IsInteger (var As Object) As Boolean
Test if the given value is integer
- IsJson (var As Object) As Boolean
Test if the object is a Json object
- IsList (var As Object) As Boolean
Test if the object is a List
- IsMap (var As Object) As Boolean
Test if the object is a Map
- IsNaN (o As Object) As Boolean
The isNaN() function determines whether a value is an illegal number (Not-a-Number).
- IsNull (var As Object) As Boolean
Test if the object is null
- IsNumber (var As Object) As Boolean
Test if the object is a number
- IsObject (var As Object) As Boolean
Test if the object is an object
- IsPhone As Boolean
Returns if the browser is running on a phone
- IsString (var As Object) As Boolean
Test if the object is a string
- IsTablet As Boolean
Returns if the browser is running on a tablet
- IsUndefined (var As Object) As Boolean
Test if the object is undefined
- Join (listOfStrings As List, delimiter As String) As String
Makes a new string from the list where all items are seperated by the delimiter
- LastIndexOf (arr As List, searchValue As Object) As Int
lastIndexOf is the same as indexOf, but returns the position of the last occurrence of the specified element.
Note: The first item has position 0, the second item has position 1, and so on.
- LastIndexOf2 (arr As List, searchValue As Object, start As Int) As Int
lastIndexOf2 is the same as indexOf2, but returns the position of the last occurrence of the specified element.
Note: The first item has position 0, the second item has position 1, and so on.
start: Where to start the search. Negative values will start at the given position counting from the end, and search to the beginning.
- LoadLayout (target As String, layoutName As String)
Loads a .bjl layout (using ONLY BANano Custom views).
You add/set BANano Custom Views in the Abstract Designer (Add View -> Custom view). Only these properties apply:
Name = HTML ID
EventName:
+ All CustomView Properties
Note: As B4J custom components currently can't set the Parent property except to main, an own algortihm tries to determine it.
layoutName must be a string. It can not be a variable.
- LoadLayoutAppend (target As String, layoutName As String)
Loads a .bjl layout (using ONLY BANano Custom views). Does not empty the Target first.
You add/set BANano Custom Views in the Abstract Designer (Add View -> Custom view). Only these properties apply:
Name = HTML ID
EventName:
+ All CustomView Properties
Note: As B4J custom components currently can't set the Parent property except to main, an own algortihm tries to determine it.
layoutName must be a string. It can not be a variable.
- LoadLayoutArray (target As String, layoutName As String, emptyTargetFirst As Boolean) As Long
Loads a .bjl layout (using ONLY BANano Custom views) as an array. You can NOT Dim one of the views in such a layout in Globals!
You add/set BANano Custom Views in the Abstract Designer (Add View -> Custom view). Only these properties apply:
Name = HTML ID
EventName:
+ All CustomView Properties
Note: As B4J custom components currently can't set the Parent property except to main, an own algortihm tries to determine it.
layoutName must be a string. It can not be a variable.
Return: will return a unique number that has been added as suffix to every view in the layout.
- Location As BANanoLocation
Returns the Location Object as a BANanoLoation.
- Map (arr As List, callbackMethod As String) As Object
The map method creates a new array by performing a function on each array element.
The map method does not execute the function for array elements without values.
The map method does not change the original array
callbackMethod should look as: Sub MyCallback(value as Object, index as int, array as List)
- MethodVarsToMap (includeSubName As Boolean) As Map
Creates a Map of all the parameters past in the current method.
If includeSubName = true, then the subs name is added with key "subname"
- Msgbox (text As String)
Shows an alert box, same as BANano.Alert
- NAN As Object
transpiles as 'NaN' (Not-a-Number)
- Navigator As BANanoNavigator
Returns the Navigator Object as a BANanoNavigator.
- New (B4JClassName As String) As Object
Creates a new instance of a B4J Class, based on its name
e.g.
Dim P1 As Page1 = BANano.New("Page1")
Log("I'm " & P1.Name)
Page1 class:
Sub Class_Globals
Public Name As String = "Page 1"
End Sub
'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
End Sub
Note: if you want to use a variable for "Page1" in BANano.New()
make sure you use BANano.BN() when you SET the variable!
see BANano.BN() for more info.
e.g.
dim myClass as String = BANano.BN("Page1")
'later in the code you can then use:
Dim P1 As Page1 = BANano.New(myClass)
Log("I'm " & P1.Name)
- ObjectToNumber (object As Object) As Int
The + operator used as a unary operator, converts its operand to a number
- OLDBROWSER As Boolean
Is a TRANSPILER CONTROL WORD to write code depending on the browser.
Older browsers which can not use ES6 keywords like Wait methods can have an alternative this way.
MUST be used like this and the if can NOT contain additional conditions!
Do NOT put this value in a variable.
e.g. If BANano.OLDBROWSER Then
' code for old browsers
Else
' code for new browsers
End If
- parseFloat (o As Object) As Double
The parseFloat() function parses a string and returns a floating point number.
- parseInt (o As Object) As Int
The parseInt() function parses a string and returns an integer.
- PHPAddHeader (header As String)
Add a header in the generated php file
e.g.
BANano.PHPAddHeader("Access-Control-Allow-Origin: *")
- PingServer (host As String, port As Int, timeoutMs As Int) As Boolean
Pings a host to check if it is reachable.
- Pop (arr As List) As Object
The pop method removes the last element from an array.
The pop method returns the value that was "popped out".
- PromiseAll (promises As List) As BANanoPromise
Returns a single Promise that resolves when all of the promises passed as a list have resolved or when the list contains no promises.
It rejects with the reason of the first promise that rejects. There is no implied ordering in the execution of the array of Promises given.
On some computers, they may be executed in parallel, or in some sense concurrently, while on others they may be executed serially.
For this reason, there must be no dependency in any Promise on the order of execution of the Promises
- PromiseAllSettled (promises As List) As BANanoPromise
Returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.
NOT supported in old browsers yet!
- PromiseAny (promises As List) As BANanoPromise
as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.
If no promises in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected.
Essentially, this method is the opposite of PromiseAll().
- PromiseRace (promises As List) As BANanoPromise
Returns a promise that fulfills or rejects as soon as one of the promises in the list fulfills or rejects, with the value or reason from that promise.
- Push (arr As List, newObj As Object) As Int
The push method adds a new element to an array (at the end).
The push method returns the new array length.
- RaiseEventToABM (eventName As String, eventParamNames As List, eventParamValues As List, Description As String)
Method to raise an event to a ABM, maximum two params because B4J only supports this maximum. Use a Map is more are needed.
The Description will be added to the generated .bas file for ABM as comment.
- Reduce (arr As List, callbackMethod As String) As Object
The reduce method runs a function on each array element to produce (reduce it to) a single value.
The reduce method works from left-to-right in the array. See also reduceRight.
The reduce method does not reduce the original array
callbackMethod should look as: Sub MyCallback(total as int, value as Object, index as int, array as List)
The total = the initial value / previously returned value
- ReduceRight (arr As List, callbackMethod As String) As Object
The reduceRight method runs a function on each array element to produce (reduce it to) a single value.
The reduceRight works from right-to-left in the array. See also reduce.
The reduceRight method does not reduce the original array.
callbackMethod should look as: Sub MyCallback(total as int, value as Object, index as int, array as List)
The total = the initial value / previously returned value
- RemoveCookie (name As String, jsonOptions As String)
Deletes a cookie.
IMPORTANT! When deleting a cookie and you're not relying on the default attributes,
you must pass the exact same path and domain attributes that were used to set the cookie
example:
RemoveCookie("mycookie", "{path: '', domain: 'mydomain.com'}")
- RemoveLocalStorage (key As String)
Deletes the key from the LocalStorage
- RemoveSessionStorage (key As String)
Deletes the key from the SessionStorage
- ReplaceRegEx (s As String, regEx As String, replacement As String) As String
The ReplaceRegEx() method returns a new string with some or all matches of a pattern replaced by a replacement
- Resolve (returnPromise As Object)
This method is called in a ...Wait() method with the signature funcNameWAIT(Resolve as Object)
see also BANano.WaitFor()
- ReturnElse (returnPromise As Object) As Object
This method is called in a function that is run by promise.CallSub()
It returns the value of the returnValue in promise.Else(returnValue)
Use Null is no returnValue is passed
Is the Reject() method in javascript
- ReturnThen (returnPromise As Object) As Object
This method is called in a function that is run by promise.CallSub()
It returns the value of the returnValue in promise.Then(returnValue)
Use Null is no returnValue is passed
Is the Resolve() method in javascript
- Reverse (arr As List)
The reverse method reverses the elements in an array.
You can use it to sort an array in descending order.
- RevokeObjectURL (url As BANanoURL)
The URL.revokeObjectURL() static method releases an existing object URL which was previously created by calling URL.createObjectURL().
Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer.
- RunInlineJavascriptMethod (methodName As String, Params As List) As Object
Will be depreciated. Use RunJavascriptMethod() instead.
- RunJavascriptMethod (methodName As String, Params As List) As Object
Method to call a Javascript method. The methodName is Case Sensitive!
For inline javascript, use #If JAVASCRIPT/#End If
Note: it does not mather where you put inline javascript, all of it is global.
Example: *
Log(BANano.RunInlineJavascriptMethod("evaluate", Array As String("10 * 20")))
#if JAVASCRIPT
function evaluate(s) {
// so we get back a string
return '' + eval(s);
}
#End If
- RunThenCatchJavascriptMethod (methodName As String, Params As List, thenCallBack As Object, catchCallBack As Object)
Method to call a Javascript method with then/catch callbacks. The methodName is Case Sensitive!
Use BANano.CallBack to build the callbacks or pass null if not used
- Screen As BANanoScreen
Returns the Screen Object as a BANanoScreen.
- SendEmail (token As String, tag As String, from As String, to As String, subject As String, body As String)
Sends a simple email
Use https://www.smtpjs.com/ to encrypt your credentials and generate the token.
It will raise the _EmailSent() event, returning the tag and a message. Can be OK or an error message.
- SetCookie (name As String, value As String, jsonOptions As String)
jsonOptions: expires, path, domain, secure
example: expires 7 days from now
SetCookie("mycookie", "myvalue", "{expires: 7, path: '', domain: 'mydomain.com', secure: 'true'}")
- SetLocalStorage (key As String, json As Object)
To set data into localStorage, you must use the SetLocalStorage API. There are two arguments:
key for the Object's key, and json for the key value
example:
dim json as JSONGenerator
json.initialize("{ founded: '1992', formed: 'California', members: ['Tom Delonge', 'Mark Hoppus', 'Travis Barker']}")
SetLocalStorage("someband", json)
- SetMeToNull
This would be the same as typing Me = Null in B4J, but this is not possible in the IDE
- SetP (Class As Object, propName As String, value As Object)
Method to set a property from any class
- SetSessionStorage (key As String, json As Object)
To set data into sessionStorage, you must use the SetSessionStorage API. There are two arguments:
key for the Object's key, and json for the key value
example:
dim json as JSONGenerator
json.initialize("{ founded: '1992', formed: 'California', members: ['Tom Delonge', 'Mark Hoppus', 'Travis Barker']}")
SetSessionStorage("someband", json)
- SetTabNotification (Number As Int)
Adds a notification number to the browsers tab. e.g. '(2) My Website'
- SF (smartFormattedText As String) As String
Returns the html conversion of a string using Smart Formatting tags.
Smart formatting Tags:
{B}{/B}: Bold
{I}{/I}: Italic
{U}{/U}: Underline
{SUB}{/SUB}: Subscript
{SUP}{/SUP}: Superscript
{BR}: Line break
{WBR}: Word break opportunity
{NBSP}: Non breakable space
{AL}http://...{AT}text{/AL}: Link, opening a new tab
{AS}http://...{AT}text{/AS}: Link, not opening a new tab
{C:#RRGGBB}{/C}: Color
{ST:styles}{/ST}: Add specific styles e.g. {ST:font-size:0.9rem;color:#2B485C}My text in font-size 0.9rem{/ST}
{IC:#RRGGBB}{/IC}: Icons (if the correct .css or font is loaded) e.g. {IC:#FFFFFF}fa fa-refresh{/IC}
- Shift (arr As List) As Object
The shift method removes the first array element and "shifts" all other elements to a lower index.
The shift method returns the string that was "shifted out".
- Sleep (milliseconds As Int)
Can only be used in a ...Wait() method.
- Slice (arr As List, start As Int) As Object
The slice method slices out a piece of an array into a new array from the start until the end.
The slice method creates a new array. It does not remove any elements from the source array.
It is like the B4J SubString for arrays.
- Slice2 (arr As List, start As Int, endNotIncluded As Int) As Object
The slice2 method slices out a piece of an array into a new array.
The slice3 method creates a new array. It does not remove any elements from the source array.
It is like the B4J SubString2 for arrays.
- Some (arr As List, callbackMethod As String) As Object
The some method checks if some array values pass a test.
callbackMethod should look as: Sub MyCallback(value as Object, index as int, array as List)
- Sort (arr As List)
The sort method sorts an array alphabetically
- Sort2 (arr As List, callbackMethod As String)
By default, the sort function sorts values as strings.
You can fix this by providing a compare function.
The compare function should return a negative, zero, or positive value, depending on the arguments.
callbackMethod should look as: Sub MyCompare(a as object, b as object) as int
If the result is negative a is sorted before b.
If the result is positive b is sorted before a.
If the result is 0 no changes are done with the sort order of the two values.
- Splice (arr As List, start As Int, length As Int, newObjs As List) As Object
The splice method can be used to add new items to an array.
The second parameter defines the position where new elements should be added (spliced in).
The third parameter defines how many elements should be removed.
The forth parameter is an array of new elements to be added.
The splice method returns an array with the deleted items.
- Split (pattern As String, text As String) As String()
Same a B4Js Regex.Split()
- Spread (variable As Object) As Object
Adds the spread operator (three dots) before the variable.
e.g. BANano.Spread(myVar)
becomes: ...myVar
- StaticFolder As String
Gets the static folder name. Is the appShortVersion if not set by BANano.TranspilerOptions.SetStaticFolder.
Can be called from within a BANano script.
- SubExists (module As Object, methodName As String) As Boolean
Will be depreciated in the future. Use the normal B4J SubExists instead!
Checks if a method exists in a module.
Note: for CallBacks, Events or CallSub, this is already done automatically
- Throw (error As Object)
The throw statement allows you to create a custom error.
Technically you can throw an exception (throw an error).
e.g. BANano.Throw("This number is not valid")
BANano.Throw(500)
- TM
Is ignored in Release mode.
Track Method. Use it in a Sub to trace some info after it ran in the browsers log.
- TMC
Is ignored in Release mode.
Same as TM (TrackMethod), but initialy collapssed
- ToBase64 (s As String) As String
Converts a string to a base 64 string.
- ToElement (obj As BANanoObject) As BANanoElement
Converts the BANanoObject to a BANAnoElement
- ToJson (object As Object) As Object
Shortcut function to make JSON of an object
- ToObject (elem As BANanoElement) As BANanoObject
Converts the BANanoElement to a BANanoObject
- ToString (o As Object) As String
The ToString() function converts the value of an object to a string.
Note: The ToString() function returns the same value as toString() of the individual objects.
- TypeOf (var As Object) As Object
Will be depreciated in the future. Use the normal B4J GetType() instead!
to get the type of the object (same as BANano.GetType)
- UNDEFINED As Object
transpiles as 'undefined' (without quotes)
- Unshift (arr As List, newObj As Object) As Int
The unshift method adds a new element to an array (at the beginning), and "unshifts" older elements.
The unshift method returns the new array length.
- UploadFile (file As Object) As BANanoPromise
Uploads a File object to the BANanoServer UploadHandler
the following request properties are added:
pageId - the unique page id
fileName - the file name
This calls a POST using the Fetch API
- UrlBase64ToUint8Array (base64String As String) As Int()
Converts a Base64 String to an unsigned int array
- WaitFor (result As Object, module As Object, methodName As String, params As List)
Waits for the methodName to be resolved
This method MUST have this signature (name must end with 'Wait' and param name must be Resolve as Object!):
e.g. methodNameWAIT(Resolve as Object, otherParam as int, ...)
Note: Do not use a BANano.AWait around this method as it already does it internally and needs some other settings before being able to run.
- Window As BANanoWindow
Returns the Window Object as a BANanoWindow.
Properties:
- BROWSERPrefix As String [write only]
Internally used by the BANanoServer lib
- ExternalTestConnectionServer As String [write only]
DEPRECIATED: Use BANano.TranspilerOptions.ExternalTestConnectionServer instead
By default the connection to the internet is tested by checking if donotdelete.gif can be retrieved
from the assets folder where the app is hosted.
However, if you do not put it on a host (e.g. just by opening the .html file from disk),
You can upload the donotdelete.gif to some host on the internet to test for an internet connection.
- Initialbody As String [write only]
Can ONLY be used in AppStart(). It writes the string directly as the innerHTML of the body tag.
- MinifyOnline As Boolean [write only]
DEPRECIATED: Use BANano.TranspilerOptions.MinifyOnline instead
Using the API of:
https://javascript-minifier.com, the generated Javascript file will be minified
https://cssminifier.com, the CSS files will be minified
- SHAREDPrefix As String [write only]
Internally used by the BANanoServer lib
- UseServiceWorker As Boolean [write only]
DEPRECIATED: Use BANano.TranspilerOptions.UseServiceWorker instead
Can ONLY be used in AppStart(). Set this param to false if you do not want to use a ServiceWorker
Default true
BANanoCacheReport
Properties:
- BANPageID As String [read only]
Returns the current unique page ID
Only useful with a B4J server, using the BANano.B4JUpdateFromCache() method
- BANSessionID As String [read only]
Returns the current session ID
Only useful with a B4J server, using the BANano.B4JUpdateFromCache() method
- ComesFromCache As Boolean [read only]
Returns if BANano could recover the B4J class from its cache
Only useful with a B4J server, using the BANano.B4JUpdateFromCache() method
- IsReconnected As Boolean [read only]
Returns if the WebSocket was reconnected
Only useful with a B4J server, using the BANano.B4JUpdateFromCache() method
BANanoConsole
Functions:
- Assert (expression As Object, message As Object)
Write a message to the console, only if the first argument is false:
- Clear
Clear all messages in the console
- Count
Writes to the console the number of times that particular Count() is called.
- Error (message As Object)
This method writes an error message to the console.
- GetField (field As String) As BANanoObject
Gets a field value
- Group (label As Object)
Creates a new inline group in the console. This indents following console messages by an additional level, until console.groupEnd() is called
- GroupCollapsed (label As Object)
Creates a new inline group in the console. However, the new group is created collapsed. The user will need to use the disclosure button to expand it
- GroupEnd
Exits the current inline group in the console
- Info (message As Object)
This method writes an info message to the console.
- Log (message As Object)
This method writes a message to the console.
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- Table (tableData As Object, tablecolumns As Object)
The console.table() method writes a table in the console view.
- Time (label As String)
Starts a timer in the console view.
- TimeEnd (label As String)
Ends a timer, and writes the result in the console view.
- Trace
Outputs a stack trace to the console
- Warn (message As Object)
This method writes an warning message to the console.
BANanoElement
Functions:
- AddClass (Class As String) As BANanoElement
Add html class(es) to all of the matched elements
- AddEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
true - The event handler is executed in the capturing phase
false - The event handler is executed in the bubbling phase
- AddEventListenerOpen (eventName As String, params As Object)
All the code between AddEventListenerOpen and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpen MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpen("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = function(aEvt) {
...
};
- AddEventListenerOpenAsync (eventName As String, params As Object)
All the code between AddEventListenerOpenAsync and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpenAsync MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpenAsync("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = async function(aEvt) {
...
};
- After (htmlOrElement As Object) As BANanoElement
Add some html as a sibling after each of the matched elements
Note: it is better to use the RenderAfter method, as it is much more powerful
- Append (htmlOrElement As Object) As BANanoElement
Add some html as a child at the end of each of the matched elements
Note: it is better to use the RenderAppend method, as it is much more powerful
- Before (htmlOrElement As Object) As BANanoElement
Add some html as a sibling before each of the matched elements
Note: it is better to use the RenderBefore method, as it is much more powerful
- Children (filter As String) As BANanoElement()
Get the direct children of all of the nodes with a filter
- ClientHeight As Double
Returns the height of an element, including padding
- ClientLeft As Double
Returns the width of the left border of an element
- ClientTop As Double
Returns the width of the top border of an element
- ClientWidth As Double
Returns the width of an element, including padding
- CloseEventListener
Closes an AddEventListenerOpen or AddEventListenerOpenAsync method
- Closest (filter As String) As BANanoElement()
Find the first ancestor that matches the selector for each node
- Empty As BANanoElement
Remove all child nodes of the matched elements.
- Filter (filter As String) As BANanoElement()
Get the direct children of the nodes with a filter
- Find (filter As String) As BANanoElement()
Get all of the descendants of the nodes with a filter
- First As BANanoElement
Retrieve the first of the matched nodes
- Get (target As Object) As BANanoElement
Gets the BANanoElement with the given ID (use '#')
- GetAttr (name As String) As String
Handle attributes for the matched elements
- GetChecked As Boolean
Retrieve the checked value of matched elements
- GetData (name As String) As String
Handle data-* attributes for the matched elements
- GetField (field As String) As BANanoObject
Gets a field value
Shortcut method for .ToObject.GetField()
- GetHTML As String
Retrieve the html of the elements
- GetScrollLeft As Double
Sets or returns the number of pixels an element's content is scrolled horizontally
- GetScrollTop As Double
Sets or returns the number of pixels an element's content is scrolled vertically
- GetStyle (property As String) As String
Returns the property value
- GetText As String
Retrieve the text content of matched elements
- GetValue As String
Retrieve the value content of matched elements
- HandleEvents (events As String, module As Object, method As String) As BANanoElement
module: the module or class where the method is defined
method: the method you want to call
This function is the same as on(), but it executes the e.preventDefault()
The method MUST be defined like this:
sub methodName(event As BANanoEvent)
log(event.ID)
end sub
- HasAttr (name As String) As Boolean
Find if any of the matched elements contains the attribute passed
- HasClass (Class As String) As Boolean
Find if any of the matched elements contains the class passed
- Initialize (target As Object)
Target: and ID (use #), class (use ."), tag etc...
- IsInitialized As Boolean
- Last As BANanoElement
Retrieve the last of the matched nodes
- Length As Int
You can check how many elements are matched with .Length
- LoadLayout (layoutName As String)
Loads a .bjl layout (using ONLY BANano Custom views).
You add/set BANano Custom Views in the Abstract Designer (Add View -> Custom view). Only these properties apply:
Name = HTML ID
EventName:
+ All CustomView Properties
Note: As B4J custom components currently can't set the Parent property except to main, an own algortihm tries to determine it.
layoutName must be a string. It can not be a variable.
Note: Must be done directly on a BANanoElement, not via a method or chaining
e.g.
Will Work:
Dim pageHolder As BANanoElement = body.Append(html).Get("#pageHolder")
pageHolder.LoadLayout("MainLayout")
Dim UserTab As BANanoElement = SKTabs1.GetTabContents(0) ' returns a BANanoElement
UserTab.LoadLayout("Users")
Will NOT work:
body.Append(html).Get("#pageHolder").LoadLayout("MainLayout")
SKTabs1.GetTabContents(0).LoadLayout("Users")
- LoadLayoutAppend (layoutName As String)
Loads a .bjl layout (using ONLY BANano Custom views). Does not empty the Target first.
You add/set BANano Custom Views in the Abstract Designer (Add View -> Custom view). Only these properties apply:
Name = HTML ID
EventName:
+ All CustomView Properties
Note: As B4J custom components currently can't set the Parent property except to main, an own algortihm tries to determine it.
layoutName must be a string. It can not be a variable.
Note: Must be done directly on a BANanoElement, not via a method or chaining
e.g.
Will Work:
Dim pageHolder As BANanoElement = body.Append(html).Get("#pageHolder")
pageHolder.LoadLayoutAppend("MainLayout")
Dim UserTab As BANanoElement = SKTabs1.GetTabContents(0) ' returns a BANanoElement
UserTab.LoadLayoutAppend("Users")
Will NOT work:
body.Append(html).Get("#pageHolder").LoadLayoutAppend("MainLayout")
SKTabs1.GetTabContents(0).LoadLayoutAppend("Users")
- LoadLayoutArray (layoutName As String, emptyTargetFirst As Boolean) As Long
Loads a .bjl layout (using ONLY BANano Custom views) as an array. You can NOT Dim one of the views in such a layout in Globals!
You add/set BANano Custom Views in the Abstract Designer (Add View -> Custom view). Only these properties apply:
Name = HTML ID
EventName:
+ All CustomView Properties
Note: As B4J custom components currently can't set the Parent property except to main, an own algortihm tries to determine it.
layoutName must be a string. It can not be a variable.
Note: Must be done directly on a BANanoElement, not via a method or chaining
e.g.
Will Work:
Dim pageHolder As BANanoElement = body.Append(html).Get("#pageHolder")
pageHolder.LoadLayout("MainLayout")
Dim UserTab As BANanoElement = SKTabs1.GetTabContents(0) ' returns a BANanoElement
UserTab.LoadLayout("Users")
Will NOT work:
body.Append(html).Get("#pageHolder").LoadLayout("MainLayout")
SKTabs1.GetTabContents(0).LoadLayout("Users")
Return: will return a unique number that has been added as suffix to every view in the layout.
- Name As String
- Not (filter As String) As BANanoElement()
Remove known nodes from nodes
- Off (events As String) As BANanoElement
Remove event handler from matched nodes
- OffsetHeight As Double
Returns the height of an element, including padding, border and scrollbar
- OffsetLeft As Double
Returns the horizontal offset position of an element
- OffsetTop As Double
Returns the vertical offset position of an element
- OffsetWidth As Double
Returns the width of an element, including padding, border and scrollbar
- On (events As String, module As Object, method As String) As BANanoElement
module: the module or class where the method is defined
method: the method you want to call
The method MUST be defined like this:
sub methodName(event As BANanoEvent)
log(event.ID)
end sub
- Parent (filter As String) As BANanoElement()
Retrieve each parent of the matched nodes, optionally filtered by a selector
- Prepend (htmlOrElement As Object) As BANanoElement
Add some html as a child at the beginning of each of the matched elements
Note: it is better to use the RenderPrepend method, as it is much more powerful
- Remove As BANanoElement
Removes the matched elements.
- RemoveAttr (name As String) As BANanoElement
Handle removing attributes for the matched elements
- RemoveClass (Class As String) As BANanoElement
Remove html class(es) to all of the matched elements.
- RemoveEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
Removes event handlers that have been attached with the addEventListener() method
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies the event phase to remove the event handler from.
true - Removes the event handler from the capturing phase
false - Removes the event handler from the bubbling phase
- Render (htmlTemplate As String, jsonData As String) As BANanoElement
Sets the innerHTML of the target using the htmlTemplate and the provided jsonData
The htmlTemplate is a Mustache template.
- RenderAfter (htmlTemplate As String, jsonData As String) As BANanoElement
Add some html as a sibling after each of the matched elements using the htmlTemplate and the provided jsonData
The htmlTemplate is a Mustache template.
- RenderAppend (htmlTemplate As String, jsonData As String) As BANanoElement
Add some html as a child at the end of each of the matched elements using the htmlTemplate and the provided jsonData
The htmlTemplate is a Mustache template.
- RenderBefore (htmlTemplate As String, jsonData As String) As BANanoElement
Add some html as a sibling before each of the matched elements using the htmlTemplate and the provided jsonData
The htmlTemplate is a Mustache template.
- RenderPrepend (htmlTemplate As String) As BANanoElement
Add some html as a child at the beginning of each of the matched elements using the htmlTemplate and the provided jsonData
The htmlTemplate is a Mustache template.
- RenderReplace (htmlTemplate As String, jsonData As String) As BANanoElement
Replaces the target using the htmlTemplate and the provided jsonData
The htmlTemplate is a Mustache template.
- Replace (html As String) As BANanoElement
Replace the matched elements with the passed elements
Note: it is better to use the RenderReplace method, as it is much more powerful
- Result As Object
Gets the result
Shortcut method for .ToObject.Result()
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- Scroll
Scroll to the first matched element, smoothly if supported.
- ScrollHeight As Double
Returns the entire height of an element, including padding
- ScrollWidth As Double
Returns the entire width of an element, including padding
- SetAttr (name As String, value As String) As BANanoElement
Handle attributes for the matched elements
- SetChecked (checked As Boolean) As BANanoElement
Set the checked value of matched elements
- SetData (name As String, value As String) As BANanoElement
Handle data-* attributes for the matched elements
- SetField (field As String, value As Object)
Sets a field value
Shortcut method for .ToObject.SetField()
- SetHTML (html As String) As BANanoElement
Set the html of the elements.
Note: it is better to use the Render method, as it is much more powerful
- SetScrollLeft (x As Double)
Sets or returns the number of pixels an element's content is scrolled horizontally
- SetScrollTop (y As Double)
Sets or returns the number of pixels an element's content is scrolled vertically
- SetStyle (jsonString As String)
Sets the style of the target BANanoElement.
example:
' must be valid Json!
BANano.GetElement("#someid").SetStyle($"{ "width": "200px", "height": "200px", "background": "green", "border-radius": "5px" }"$)
- SetText (text As String) As BANanoElement
Set the text content of matched elements
- SetValue (text As String) As BANanoElement
Set the value content of matched elements
- Siblings (filter As String) As BANanoElement()
Get the siblings of all of the nodes with a filter
- ToggleClass (Class As String) As BANanoElement
Toggles the class of matched elements
- ToObject As BANanoObject
Returns a BANanoObject: nodes[0], the native html object
- Trigger (event As String, params As String()) As BANanoElement
Triggers an event.
Params: MUST be defined as Array("", 0, ...)
Will be returned in the event.detail property
- Wrap (html As String) As BANanoElement
Wraps the matched element(s) with the passed argument. It accepts an html tag like .wrap('<div>')
BANanoEvent
Fields:
Functions:
- AltKey As Boolean
- Buttons As Int
- Char As String
- CharCode As String
- ClientX As Int
- ClientY As Int
- CtrlKey As Boolean
- CurrentTarget As Object
- Data As Object
- DeltaMode As Int
- DeltaX As Int
- DeltaY As Int
- DeltaZ As Int
- Detail As Object()
- ID As String
- Key As String
- KeyCode As String
- MetaKey As Boolean
- OffsetX As Int
- OffsetY As Int
- OtherField (field As String) As BANanoObject
Gets another field value
- PageX As Int
- PageY As Int
- PreventDefault As Object
- Reason As Object
- RelatedTarget As Object
- ScreenX As Int
- ScreenY As Int
- ShiftKey As Boolean
- StopPropagation As Object
- Target As Object
- TimeStamp As Int
- Type As String
- Value As Object
Properties:
BANanoFetch
Functions:
- Else (error As Object)
Continues here after the Fetch if an error occurs.
- ElseWait (returnValue As Object)
Is the same as .Else, except the function will be async.
This can be used if the code in the .ElseWait clause contains ...Wait functions or Sleep
- End
Terminates the promise Then/Else/Finally
- Finally
Will always run at the end
- FinallyWait
Is the same as .Finally, except the function will be async.
This can be used if the code in the .FinallyWait clause contains ...Wait functions or Sleep
- Initialize (resource As String, init As BANanoFetchOptions) As BANanoPromise
Does a Fetch with a resource (e.g. url) and an optional Request options object
Pass null if no request options need to be set
- Return (data As Object)
Returns something in a then part. Can be passed on the the next then.
- Then (response As Object)
Continues here after the Fetch or another then/else
- ThenWait (returnValue As Object)
Is the same as .Then, except the function will be async.
This can be used if the code in the .ThenWait clause contains ...Wait functions or Sleep
BANanoFetchOptions
Functions:
- GetField (field As String) As BANanoObject
Gets a field value
- Initialize
Creates a new options object.
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
Properties:
- Body As Object
Any body that you want to add to your request: this can be a Blob, BufferSource, FormData,
URLSearchParams, or USVString object.
Note that a request using the GET or HEAD method cannot have a body.
- Cache As String
The cache mode you want to use for the request.
- Credentials As Object
The request credentials you want to use for the request: omit, same-origin, or include.
To automatically send cookies for the current domain, this option must be provided.
Starting with Chrome 50, this property also takes a FederatedCredential instance or a PasswordCredential instance.
- Headers As Object
Any headers you want to add to your request, contained within a Headers object or an object literal with ByteString values.
Note that some names are forbidden.
- Integrity As String
Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
- KeepAlive As Boolean
The keepalive option can be used to allow the request to outlive the page.
- Method As String
The request method, e.g., GET, POST.
Default: GET
- Mode As String
The mode you want to use for the request, e.g., cors, no-cors, or same-origin.
- Redirect As String
The redirect mode to use: follow (automatically follow redirects),
error (abort with an error if a redirect occurs), or manual (handle redirects manually).
In Chrome the default is follow (before Chrome 47 it defaulted to manual).
- Referrer As String
A USVString specifying no-referrer, client, or a URL. The default is client.
- ReferrerPolicy As String
Specifies the value of the referer HTTP header. May be one of no-referrer,
no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
- Signal As Object
An AbortSignal object instance; allows you to communicate with a fetch request and abort it if desired via an AbortController.
BANanoFetchResponse
Functions:
- ArrayBuffer As Object
Takes a Response stream and reads it to completion. It returns a promise that resolves with an ArrayBuffer.
- Blob As Object
Takes a Response stream and reads it to completion. It returns a promise that resolves with a Blob.
- Body As Object
A simple getter used to expose a ReadableStream of the body contents.
- BodyUsed As Boolean
Stores a Boolean that declares whether the body has been used in a response yet.
- Clone As BANanoFetchResponse
Creates a clone of a Response object.
- Error As BANanoFetchResponse
Returns a new Response object associated with a network error.
- FormData As Object
Takes a Response stream and reads it to completion. It returns a promise that resolves with a FormData object.
- GetField (field As String) As BANanoObject
Gets a field value
- Headers As Object
Contains the Headers object associated with the response.
- Initialize
Creates a new Response object.
- Json As Object
Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.
- OK As Boolean
Contains a boolean stating whether the response was successful (status in the range 200-299) or not.
- Redirect (url As String, Status As Int) As BANanoFetchResponse
The redirect() method returns a Response resulting in a redirect to the specified URL.
Status is optional, pass null if not used.
- Redirected As Boolean
Indicates whether or not the response is the result of a redirect; that is, its URL list has more than one entry.
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- Status As Int
Contains the status code of the response (e.g., 200 for a success).
- StatusText As String
Contains the status message corresponding to the status code (e.g., OK for 200).
- Text As Object
Takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString (text).
- Type As String
Contains the type of the response (e.g., basic, cors).
- Url As String
Contains the URL of the response.
Properties:
- UseFinalUrl As Boolean
State whether this is the final URL of the response.
BANanoGeoLocation
Functions:
- ClearWatch (watchID As Int)
Stops the watchPosition() method.
- GetCurrentPosition (PositionCallback As Object, ErrorCallback As Object)
Only works with https!
Return the user's position
PositionCallback: MUST look like functionName(position AS BANanoGeoPosition)
ErrorCallback: MUST look like functionName(error As int):
1: Permission Denied
2: Position Unavailable
3: Timeout
Else: Unknown error
- GetField (field As String) As BANanoObject
Gets a field value
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- WatchPosition (PositionCallback As Object, ErrorCallback As Object) As Int
Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
PositionCallback: MUST look like functionName(position AS BANanoGeoPosition)
ErrorCallback: MUST look like functionName(error As BANanoGeoError)
Returns a watch id that then can be used to unregister the handler by passing it to the Geolocation.clearWatch() method
BANanoGeoPosition
Functions:
- Accuracy As Double
The accuracy of position (always returned)
- Altitude As Double
The altitude in meters above the mean sea level (returned if available)
- AltitudeAccuracy As Double
The altitude accuracy of position (returned if available)
- Heading As Double
The heading as degrees clockwise from North (returned if available)
- Latitude As Double
The latitude as a decimal number (always returned)
- Longitude As Double
The longitude as a decimal number (always returned)
- Speed As Double
The speed in meters per second (returned if available)
- Timestamp As Double
The date/time of the response (returned if available)
BANanoHeader
Fields:
- Author As String
- BackgroundColor As String
- BaseTarget As String
- BaseURL As String
- Charset As String
- Description As String
- Expires As Long
- Keywords As String
- Language As String
- Manifest As String
- MaskIconColor As String
- MSTileColor As String
- OnDOMContentLoaded As String
- ThemeColor As String
- Title As String
- Viewport As String
Functions:
- AddAppleTouchIcon (AssetFileNameOrURL As String, size As String)
home screen icons for Safari and iOS. Size e.g. 16x16.
- AddCSSFile (AssetFileNameOrURL As String)
Load an extra css file. If it is an asset file it will be copied to the styles folder
For locale files (not URLs), you can use the * wildcard
- AddCSSFileForLater (AssetFileNameOrURL As String)
Load an extra css file. If it is an asset file it will be copied to the styles folder
This asset will not be loaded at loading the html file, but you will have to do it 'Later' using the BANano.AssetsLoad... methods
For locale files (not URLs), you can use the * wildcard
- AddFavicon (AssetFileNameOrURL As String, size As String)
Add additional fav icons. Size e.g. 16x16.
- AddJavascriptES6File (AssetFileName As String)
Load an extra ES6 javascript file. It must be an asset file and can not be an url.
You can use the * wildcard
- AddJavascriptES6FileForLater (AssetFileName As String)
Load an extra ES6 javascript file. It must be an asset file and can not be an url.
This asset will not be loaded at loading the html file, but you will have to do it 'Later' using the BANano.AssetsLoad... methods
You can use the * wildcard
- AddJavascriptFile (AssetFileNameOrURL As String)
Load an extra javascript file. If it is an asset file it will be copied to the scripts folder
For locale files (not URLs), you can use the * wildcard
- AddJavascriptFileForLater (AssetFileNameOrURL As String)
Load an extra javascript file. If it is an asset file it will be copied to the scripts folder
This asset will not be loaded at loading the html file, but you will have to do it 'Later' using the BANano.AssetsLoad... methods
For locale files (not URLs), you can use the * wildcard
- AddJavascriptFileForLaterSW (AssetFileNameOrURL As String)
Does the same a AddJavascriptFileForLater() but will write in also in the ImportScripts() method in the Service Worker file.
NOTE:such a javascript file can NOT use window or document or any other reference to the DOM as a Service Worker can not access this!
If it is a javascript file used in a BANanoLibrary, it MUST be added in the app explicitly!
These javascript files will NOT be merged!
- AddJavascriptFileSW (AssetFileNameOrURL As String)
Does the same a AddJavascriptFile() but will write in also in the ImportScripts() method in the Service Worker file.
NOTE:such a javascript file can NOT use window or document or any other reference to the DOM as a Service Worker can not access this!
If it is a javascript file used in a BANanoLibrary, it MUST be added in the app explicitly!
These javascript files will NOT be merged!
- AddManifestIcon (AssetFileNameOrURL As String, size As String)
PWA Icon used in the manifest.json file. Size e.g. 16x16.
- AddMeta (metaTag As String)
must be a full html meta tag. Use smartstrings! e.g.
$"<meta name="keywords" content="HTML,CSS,XML,JavaScript">"$
- AddMSTileIcon (AssetFileNameOrURL As String, size As String)
home screen icons for Microsoft. Size e.g. 16x16.
- SetMaskIcon (AssetFileNameOrURL As String)
Set the Mask Icon
BANanoHistory
Functions:
- Back
Go back to the previous page
- Forward
Go to the next page
- GetField (field As String) As BANanoObject
Gets a field value
- Go (step As Int)
Navigate back or forward multiple levels deep
- Length As Int
Number of entries in the history
- PushState (state As Object, url As Object)
Create a new history entry programmatically
State must be serializable and is limited in size.
Note that the URL needs to belong to the same origin domain of the current URL.
- ReplaceState (state As Object, url As Object)
Allows you to edit the current history state.
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
Properties:
- State As Object [read only]
Returns the current state object
BANanoJSONGenerator
Functions:
- Initialize (Map As Map)
Initializes the object with the given Map.
- Initialize2 (List As List)
Initializes the object with the given List.
- ToPrettyString (Indent As Int) As String
Creates a JSON string from the initialized object.
The string will be indented and easier for reading.
Note that the string created is a valid JSON string.
Indent - Number of spaces to add to each level.
- ToString As String
Creates a JSON string from the initialized object.
This string does not include any extra whitespace.
BANanoJSONParser
Functions:
- Initialize (Text As String)
Initializes the object and sets the text that will be parsed.
- NextArray As List
- NextObject As Map
Parses the text assuming that the top level value is an object.
BANanoJSONQuery
Functions:
- All As List
Returns all records.
- Count As Int
Returns the number of records.
- Find (field As String, value As Object) As Map
Returns the first record, matching the field with the passed value.
- First As Map
Returns the first record.
- GroupBy (field As String) As BANanoJSONQuery
Returns a Map where all records are grouped by field.
The key in the map is the group field, the value is a list of records matching the group field.
- Initialize (json As Object)
Initializes with a Json Object (must be an array of records).
- Initialize2 (jsonString As String)
Initializes with a Json String.
- Last As Map
Returns the last record.
- Limit (limit As Int) As BANanoJSONQuery
Limits the number of records returned. Often used together with Offset.
e.g. .Limit(5).Offset(20).All returns records 21,22,23,24,25
- Offset (offset As Int) As BANanoJSONQuery
Offset in the recordset. Often used together with Limit.
e.g. .Limit(5).Offset(20).All returns records 21,22,23,24,25
- Order (jsonOrder As String) As BANanoJSONQuery
Orders the result of the query.
"{'FieldName' : 'desc/asc', ...}"
- OrWhere (jsonSelector As String) As BANanoJSONQuery
Must be used after a Where.
A selector is a string in this format:
"{'FieldName.Operator' : value, ...}"
*
e.g. .Where(...).OrWhere("{'rating.$eq': 8.4, 'name.$li': /braveheart/i"}")
if the operator is omitted, .$eq is used.
Possible operators:
.$eq: Equal
.$ne: Not Equal
.$lt: Less than
.$gt: Greater than
.$bt: Between (expects an Array, e.g. [4, 6])
.$in: In (expects an Array, e.g. [6,15])
.$ni: Not in (expects an Array, e.g. [6,15])
.$li: Like (expects a String or a regex expression)
- Pluck (field As String) As List
Returns an array containing all values of field.
- SelectFields (fields As List) As BANanoJSONQuery
Returns an array of json objects with a subset of only the fields past .
- ToJQ As BANanoJSONQuery
Returns a subset of the records, using the query settings.
The result is a new BANanoJSONQuery object.
e.g.
Dim resultJQ as BANanoJSONQuery
resultJQ = placesJQ.Where("'name': 'Bayview'").ToJQ
resultJQ.Where("'types.$eq': 'polictical'").All
- Unique (field As String) As BANanoJSONQuery
Returns a List with the unique values of a field.
- Where (jsonSelector As String) As BANanoJSONQuery
A selector is a string in this format:
"{'FieldName.Operator' : value, ...}"
e.g. .Where("{'rating.$eq': 8.4, 'name.$li': /braveheart/i}")
if the operator is omitted, .$eq is used.
Possible operators:
.$eq: Equal
.$ne: Not Equal
.$lt: Less than
.$gt: Greater than
.$bt: Between (expects an Array, e.g. [4,6])
.$in: In (expects an Array, e.g. [6,15])
.$ni: Not in (expects an Array, e.g. [6,15])
.$li: Like (expects a String or a regex expression)
BANanoLocation
Functions:
- Assign (URL As String)
The assign() method loads a new document.
The difference between this method and replace(), is that replace() removes the URL of the current document from the document history,
meaning that it is not possible to use the 'back' button to navigate back to the original document.
- GetField (field As String) As BANanoObject
Gets a field value
- GetHash As String
Sets or returns the anchor part (#) of a URL
- GetHost As String
Sets or returns the hostname and port number of a URL
- GetHostName As String
Sets or returns the hostname of a URL
- GetHref As String
Sets or returns the entire URL
- GetPathName As String
Sets or returns the path name of a URL
- GetPort As Int
Sets or returns the port number of a URL
- GetProtocol As String
Sets or returns the protocol of a URL
- GetSearch As String
Sets or returns the querystring part of a URL
- Reload (forceGet As Boolean)
he reload() method is used to reload the current document.
The reload() method does the same as the reload button in your browser.
By default, the reload() method reloads the page from the cache, but you can force it to reload the page
from the server by setting the forceGet parameter to true
- Replace (newURL As String)
The replace() method replaces the current document with a new one.
The difference between this method and assign(), is that replace() removes the URL of the current document from the document history,
meaning that it is not possible to use the 'back' button to navigate back to the original document.
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- SetHash (hash As String)
Sets or returns the anchor part (#) of a URL
- SetHost (host As String)
Sets or returns the hostname and port number of a URL
- SetHostName (hostName As String)
Sets or returns the hostname of a URL
- SetHref (href As String)
Sets or returns the entire URL
- SetPathName (pathName As String)
Sets or returns the path name of a URL
- SetPort (port As Int)
Sets or returns the port number of a URL
- SetProtocol (protocol As String)
Sets or returns the protocol of a URL
- SetSearch (search As String)
Sets or returns the querystring part of a URL
Properties:
- Origin As String [read only]
Returns the protocol, hostname and port number of a URL
BANanoMQTTClient
Events:
- Connected (Success As Boolean)
- Disconnected
- MessageArrived (Topic As String, Payload() As Byte)
Functions:
- Close
- Connect
- Connect2 (Options As BANanoMQTTConnectOptions)
- Initialize (EventName As String, Server As String, port As Int, path As String, isSecure As Boolean, ClientID As String)
Only Websockets are supported
- Publish (Topic As String, Payload As Byte())
- Publish2 (Topic As String, Payload As Byte(), QOS As Int, Retained As Boolean)
- Subscribe (Topic As String, QOS As Int)
- Unsubscribe (Topic As String)
Properties:
- ClientID As String [read only]
- QOS_0_MOST_ONCE As Int [read only]
- QOS_1_LEAST_ONCE As Int [read only]
- QOS_2_EXACTLY_ONCE As Int [read only]
BANanoMQTTConnectOptions
Functions:
- Initialize (UserName As String, Password As String)
Initializes the object and sets the username and password.
Pass empty strings if username or password are not required.
- SetLastWill (Topic As String, Payload As Byte(), QOS As Int, Retained As Boolean)
Properties:
- CleanSession As Boolean [write only]
If set to true (default value) then the state will not be preserved in the case of client restarts.
- Password As String
Gets or sets the connection password.
- UserName As String
Gets or sets the connection user name.
BANanoMediaQuery
Events:
Functions:
- GetField (field As String) As BANanoObject
Gets a field value
- Initialize (mediaQueryList As String)
mediaQueryList examples:
(max-width: 400px)
(min-width: 401px) and (max-width: 600px)
(min-width: 601px) and (max-width: 800px)
(min-width: 801px)
(orientation: portrait)
(orientation: landscape)
- IsInitialized As Boolean
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
BANanoMutationObserver
Events:
- CallBack (records() As BANanoMutationRecord, observer As BANanoMutationObserver)
Functions:
- Disconnect
Stops the MutationObserver instance from receiving further notifications until and unless Observe() is called again.
- GetField (field As String) As BANanoObject
Gets a field value
- Initialize (callbackEventName As String)
callbackEventName: the eventName of the CallBack event.
' record: A BANanoMutationRecord represents an individual DOM mutation.
' observer: this observer
Sub EventName_CallBack(record As BANanoMutationRecord, observer As BANanoMutationObserver)
End Sub
- Observe (target As Object)
target: Which node (or parent node) to observe
Will use the settings on this object.
At least one of the following has to be set to true for it to work.
.Attributes
.ChildList
.CharacterData
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- TakeRecords As BANanoMutationRecord()
returns an array of all matching DOM changes that have been detected but not yet processed by the observer's callback function,
leaving the mutation queue empty. The most common use case for this is to immediately fetch all pending mutation records
immediately prior to disconnecting the observer, so that any pending mutations can be processed when stopping down the observer.
Properties:
- AttributeFilter As List [write only]
An array of DOMString objects, each specifying the name of one attribute whose value is to be monitored for changes.
There is no default value.
- AttributeOldValue As Boolean [write only]
A Boolean value indicating whether or not the prior value of a changed attribute should be included in the MutationObserver.oldValue property
when reporting attribute value changes. If true, oldValue is set accordingly. If false, it is not.
When using attributeOldValue, setting the attributes option to true is optional.
- Attributes As Boolean [write only]
A Boolean value indicating whether or not to report through the callback any changes to the values of attributes on the node or nodes being monitored.
The default value is false.
If true, the callback specified when observe() was used to start observing the node or subtree will be called any time one or more attributes have changed on observed nodes.
You can expand the capabilities of attribute mutation monitoring using other options:
attributeFilter lets you specify specific attribute names to monitor instead of monitoring all attributes.
attributeOldValue lets you specify whether or not you want the previous value of changed attributes to be included in the MutationRecord's oldValue property.
subtree lets you specify whether to watch the target node and all of its descendants (true), or just the target node (false).
If you set either attributeFilter or attributeOldValue to true, attributes is automatically assumed to be true, even if you don't expressly set it as such.
- CharacterData As Boolean [write only]
A Boolean value indicating whether or not to call the observer's callback function when textual nodes' values change.
If true, the callback specified when observe() was used to start observing the node or subtree is called any time the contents of a text node are changed.
You can expand the capabilities of attribute mutation monitoring using other options:
characterDataOldValue lets you specify whether or not you want the previous value of changed text nodes to be provided using the MutationRecord's oldValue property.
subtree lets you specify whether to watch the target node and all of its descendants (true), or just the target node (false).
If you set characterDataOldValue to true, characterData is automatically assumed to be true, even if you don't expressly set it as such.
- CharacterDataOldValue As Boolean [write only]
A Boolean value indicating whether or not to set the MutationRecord's oldValue property to be a string containing the value of
the character node's contents prior to the change represented by the mutation record.
By default, only changes to the text of the node specified as the target parameter when you called observe() are monitored.
To watch for changes to the text contents of all descendants of target, set the subtree option to true.
If you set characterDataOldValue to true, characterData is automatically assumed to be true, even if you don't expressly set it as such.
- ChildList As Boolean [write only]
A Boolean value indicating whether or not to invoke the callback function when new nodes are added to or removed from the section of the DOM being monitored.
If subtree is false, only the node indicated by the observer's target node is monitored for changes. Setting subtree to true causes addition or removal of nodes
anywhere within the subtree rooted at target to be reported.
- SubTree As Boolean [write only]
Set to true to extend monitoring to the entire subtree of nodes rooted at target. All of the other MutationObserverInit properties are then extended to all of the nodes
in the subtree instead of applying solely to the target node.
The default value is false.
BANanoMutationRecord
Functions:
- AddedNodes As BANanoObject()
Return the nodes added. Will be empty if no nodes were added.
- AttributeName As String
Returns the local name of the changed attribute, or null.
- AttributeNamespace As String
Returns the namespace of the changed attribute, or null.
- GetField (field As String) As BANanoObject
Gets a field value
- NextSibling As BANanoObject
Return the next sibling of the added or removed nodes, or null.
- OldValue As String
The return value depends on the MutationRecord.type.
For attributes, it is the value of the changed attribute before the change.
For characterData, it is the data of the changed node before the change.
For childList, it is null.
- PreviousSibling As BANanoObject
Return the previous sibling of the added or removed nodes, or null.
- RemovedNodes As BANanoObject()
Return the nodes removed. Will be empty if no nodes were removed.
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- Target As BANanoObject
Returns the node the mutation affected, depending on the Type.
For attributes, it is the element whose attribute changed.
For characterData, it is the CharacterData node.
For childList, it is the node whose children changed.
- TypeRecord As String
Returns
"attributes" if the mutation was an attribute mutation,
"characterData" if it was a mutation to a CharacterData node,
"childList" if it was a mutation to the tree of nodes.
BANanoNavigator
Functions:
- AppCodeName As String
Returns the code name of the browser
- AppName As String
Returns the name of the browser
- AppVersion As String
Returns the version information of the browser
- CookieEnabled As Boolean
Determines whether cookies are enabled in the browser
- GetField (field As String) As BANanoObject
Gets a field value
- JavaEnabled As Boolean
Specifies whether or not the browser has Java enabled
- Language As String
Returns the language of the browser
- OnLine As Boolean
Determines whether the browser is online
- Platform As String
Returns for which platform the browser is compiled
- Product As String
Returns the engine name of the browser
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- UserAgent As String
Returns the user-agent header sent by the browser to the server
BANanoObject
Functions:
- AddEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
true - The event handler is executed in the capturing phase
false - The event handler is executed in the bubbling phase
- AddEventListenerOpen (eventName As String, params As Object)
All the code between AddEventListenerOpen and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpen MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpen("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = function(aEvt) {
...
};
- AddEventListenerOpenAsync (eventName As String, params As Object)
All the code between AddEventListenerOpenAsync and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpenAsync MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpenAsync("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = async function(aEvt) {
...
};
- ClientHeight As Double
Returns the height of an element, including padding
- ClientLeft As Double
Returns the width of the left border of an element
- ClientTop As Double
Returns the width of the top border of an element
- ClientWidth As Double
Returns the width of an element, including padding
- CloseEventListener
Closes an AddEventListenerOpen or AddEventListenerOpenAsync method
- Delete (property As String)
The delete operator deletes a property from an object
- Execute (params As List) As BANanoObject
If BANanoObject is a function, then you can execute it directly with params.
- GetField (field As String) As BANanoObject
Gets a field value
- GetFunction (functionName As String) As BANanoObject
Gets a function. You can then directly call the Execute method on it.
- GetScrollLeft As Double
Sets or returns the number of pixels an element's content is scrolled horizontally
- GetScrollTop As Double
Sets or returns the number of pixels an element's content is scrolled vertically
- HasOwnProperty (propName As String) As Boolean
Check whether a property is inherited
- Initialize (jsObject As Object)
Can be used e.g. to connect a BANanoObject to a JavaScript object
- Initialize2 (jsObject As String, params As Object) As BANanoObject
To initialize for a 'New libObjectName' javascript library
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
see RunMethod for more info on the Array system.
e.g. Javascript:
let datepicker = new When({
input: document.getElementById('...'),
singleDate: true
});
datepicker.showHeader = true;
Translated to B4J:
Dim datepicker As BANanoObject
datepicker.Initialize2("When", CreateMap("input": BANano.GetElement("#datepicker").ToObject, "singleDate": True))
datepicker.RunMethod("showHeader", True)
- Initialize3 (params As Object) As BANanoObject
Initialize using a constructor on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
Initialize3(Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
Initialize3("Alain")
- Initialize4 (jsObject As String, params As Object) As BANanoObject
Can be used e.g. to connect a BANanoObject to a JavaScript object, with parameters
This is basically the .Initialize, but with parameters. It does NOT do a New like the Initialize2 method!
- Initialize5 As BANanoObject
Can be used create a plain Javascript object
This is basically set the object in Javascript to {}
- IsInitialized As Boolean
- OffsetHeight As Double
Returns the height of an element, including padding, border and scrollbar
- OffsetLeft As Double
Returns the horizontal offset position of an element
- OffsetTop As Double
Returns the vertical offset position of an element
- OffsetWidth As Double
Returns the width of an element, including padding, border and scrollbar
- RemoveEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
Removes event handlers that have been attached with the addEventListener() method
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies the event phase to remove the event handler from.
true - Removes the event handler from the capturing phase
false - Removes the event handler from the bubbling phase
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- ScrollHeight As Double
Returns the entire height of an element, including padding
- ScrollWidth As Double
Returns the entire width of an element, including padding
- Selector (selector As Object) As BANanoObject
Useful for e.g. jQuery selectors
Dim jQ as BANanoObject
jQ.Initialize("$")
JQ.Selector("#btn2").RunMethod("Click", Array(BANano.CallBack(Me, "btn2_clicked", Null))))
Sub Btn2_Clicked()
BANano.Msgbox("btn2 clicked through BANanoObject and jQuery!")
End Sub
- SetField (field As String, value As Object)
Sets a field value
- SetScrollLeft (x As Double)
Sets or returns the number of pixels an element's content is scrolled horizontally
- SetScrollTop (y As Double)
Sets or returns the number of pixels an element's content is scrolled vertically
BANanoPromise
Functions:
- CallSub (module As Object, methodName As String, params As List)
Calls a method. This method must use BANano.ReturnThen and/or BANano.ReturnElse to finish the method.
e.g.
Sub AFunction()
Dim returnValue As Long 'ignore
Dim promise As BANanoPromise
promise.CallSub(Me, "myfuncwait", Array(25))
promise.Then(returnValue)
Log("The sum < 150 " & returnValue)
promise.else(returnValue)
Log("rejected: > 150 " & returnValue)
promise.End
End Sub
public Sub myFuncWait(toAdd As Long)
If 100 + toAdd < 150 Then
BANano.ReturnThen(100 + toAdd)
End If
Sleep(5000)
BANano.ReturnElse(100 + toAdd)
End Sub
- Else (returnValue As Object)
Continues here after the CallSub with the returnValue from ReturnElse.
See CallSub() for an example.
- ElseWait (returnValue As Object)
Is the same as .Else, except the function will be async.
This can be used if the code in the .ElseWait clause contains ...Wait functions or Sleep
- End
Terminates the promise Then/Else/Finally
- Finally
Will always run at the end
- FinallyWait
Is the same as .Finally, except the function will be async.
This can be used if the code in the .FinallyWait clause contains ...Wait functions or Sleep
- IsInitialized As Boolean
- NewEnd
Close a NewStart or NewStartWait.
- NewStart
Make a new Promise with this signature:
Dim prom as BANanoPromise
prom.NewStart
...
BANano.ReturnThen(ret)
...
BANano.ReturnElse(ret)
prom.NewEnd
prom.Then(response)
prom.Else(response)
prom.End
Transpiles to:
prom = new Promise(function(resolve, reject) {
...
resolve(ret);
...
reject(ret)
});
prom.then(function(response) {
}).else(function(response) {
});
Example:
Dim response As String
Dim prom As BANanoPromise 'ignore
prom.NewStart
BANano.ReturnThen("Alain")
prom.NewEnd
prom.Then(response)
Return "Hello " & response & "!" 'ignore
prom.Then(response) 'ignore
Log(response) ' prints: Hello Alain!
prom.end
- NewStartWait
Same as NewStart, but needed if you use Wait methods
Example:
Dim response As String
Dim prom As BANanoPromise 'ignore
prom.NewStartWait
Sleep(3000) ' is a Wait method
BANano.ReturnThen("Alain")
prom.NewEnd
prom.Then(response)
Return "Hello " & response & "!" 'ignore
prom.Then(response) 'ignore
Log(response) ' prints: Hello Alain!
prom.end
- Then (returnValue As Object) As BANanoPromise
Continues here after the promise.CallSub with the returnValue from ReturnThen.
See CallSub() for an example.
- ThenWait (returnValue As Object)
Is the same as .Then, except the function will be async.
This can be used if the code in the .ThenWait clause contains ...Wait functions or Sleep
BANanoRegEx
Functions:
- Exec (s As String) As String
Tests for a match in a string. Returns the first match
- ExecAll (s As String) As String()
Tests for a match in a string. Returns all matches
- GetIndex (execResult As String()) As Int
The 0-based index of the match in the string.
- Global As Boolean
Checks whether the "g" modifier is set
- IgnoreCase As Boolean
Checks whether the "i" modifier is set
- InitializePattern (pattern As String)
Creates a new BANanoRegEx object using the given pattern
the outer quotes will be removed
see Javascript RegEx reference for the pattern.
- InitializeString (patternS As String)
Creates a new BANanoRegEx object using the given string
see Javascript RegEx reference for the pattern.
- LastIndex As Int
The lastIndex property specifies the index at which to start the next match.
- MultiLine As Boolean
Check whether or not the "m" modifier is set
- ReplacePattern (s As String, pattern As String, byStr As String) As String
The replace() method replaces a specified value with another value in a string
you don't need to use BANano.RegEx to initiate it.
- ReplaceString (s As String, patternS As String, byStr As String) As String
The replace() method replaces a specified value with another value in a string
the outer quotes will be removed
you don't need to use BANano.RegEx to initiate it.
- SearchPattern (s As String, pattern As String) As Int
The search() method searches a string for a specified value and returns the position of the match
the outer quotes will be removed
you don't need to use BANano.RegEx to initiate it.
- SearchString (s As String, patternS As String) As Int
The search() method searches a string for a specified value and returns the position of the match
you don't need to use BANano.RegEx to initiate it.
- Source As String
Return the text of the RegExp pattern
- Test (s As String) As Boolean
Tests for a match in a string. Returns true or false
BANanoSQL
Events:
- SQLExecuteError (Tag As String, Reason As String)
- SQLExecuteResult (Tag As String, Result As List)
- SQLOpened()
Functions:
- Execute (Query As String, Args As List, tag As String)
Will return the result in the SQLResult(Tag as String, Result as List) event. The tag can be used to see where it is coming from.
Result returns a list of maps containing the requested data in case of a SELECT
if an error occurs, SQLExecuteError() will be raised with Tag you passed
- ExecuteCallback (Query As String, Args As List, module As Object, methodName As String)
Will return the result in the callback. MUST BE defined as:
functionName(success As Boolean, Result as List, Reason as String)
Result returns a list of maps containing the requested data in case of a SELECT
- ExecuteWait (Query As String, Args As List) As List
Returns the result as a List of maps containing the requested data in case of a SELECT
Note: Do not use a BANano.AWait around this method as it already does it internally and needs some other settings before being able to run.
- LastInserted (tableName As String, fieldName As String) As Object
Returns the last auto incremented value after an insert
- NextInserted (tableName As String, fieldName As String) As Object
Returns the next auto incremented value that will be used
- Open (eventName As String, databaseName As String)
Opens the database and creates it if it does not exist. Uses IndexedDB so everything works with promises.
When the database is created and open the event SQLOpened() will be raised
if an error occurs, SQLExecuteError() will be raised with Tag="CREATEDB"
- OpenWait (eventName As String, databaseName As String)
Opens the database and creates it if it does not exist. Uses IndexedDB so everything works with promises.
Note: Do not use a BANano.AWait around this method as it already does it internally and needs some other settings before being able to run.
BANanoScreen
Functions:
- AvailHeight As Double
Returns the height of the screen (excluding the Windows Taskbar)
- AvailWidth As Double
Returns the width of the screen (excluding the Windows Taskbar)
- ColorDepth As Double
Returns the bit depth of the color palette for displaying images
- GetField (field As String) As BANanoObject
Gets a field value
- Height As Double
Returns the total height of the screen
- PixelDepth As Double
Returns the color resolution (in bits per pixel) of the screen
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- Width As Double
Returns the total width of the screen
BANanoTranspilerOptions
Functions:
- DoNotDeleteFolderOnCompilation (fullPath As String)
Prevents the Transpiler from deleting this folder. Useful e.g. for assets that are not in the /Files folder.
- GZipGeneratedWebsite (minSizeKB As Double)
Will GZip your html/css/js/json files on compilation. Set a minimum filesize so small files are not compressed
This is ONLY useful if you use NGinx with gzip_static set to 'on'
- IgnoreB4JLibrary (libName As String)
A B4J library the BANano Transpiler should ignore.
By default, the following are ignored:
BANano
BANanoServer
jCore
jFx
jServer
JavaObject
ABJJWT
- RedirectOutput (dir As String, fileName As String)
Reirects the logs to a file. Must be set in AppStart
- SetFireReadyWhenReadyStateComplete (bool As Boolean)
Raises the Ready state only when the loading state is 'Complete'. Default = True
- SetIgnoreAutoID (ignore As Boolean)
Ignore Transpiling the AutoID property of a CustomView to a random ID/Name.
- SetSessionMaxInactiveInterval (sessionMaxInactiveInterval As Int)
Sends a heartbeat. Only applicable if a BANanoServer is used.
Should be the same a the BANanoServer.SessionMaxInactiveInterval
- SetStaticFolder (staticFolderName As String)
Sets the static folder name. is by default the appShortVersion. Can only be set in AppStart, after the initialize.
Properties:
- Author As String [write only]
Must be set before Build(). Only applicable for .b4xlibs.
- EnableLiveCodeSwapping As Boolean [write only]
Enable Live Code Swapping and watch live changes made in the B4J source code.
On Save, the changed B4J code is Transpiled again and reloaded by the browser.
Default = true
- ExternalTestConnectionServer As String [write only]
By default the connection to the internet is tested by checking if donotdelete.gif can be retrieved
from the assets folder where the app is hosted.
However, if you do not put it on a host (e.g. just by opening the .html file from disk),
You can upload the donotdelete.gif to some host on the internet to test for an internet connection.
- IDEComment As String [write only]
Must be set before Build(). Only applicable for .b4xlibs.
- IgnoreWarningsOldBrowsers As Boolean [write only]
If True the transpiler will not show warnings for older browsers
- MergeAllCSSFiles As Boolean [write only]
Must be set before Build(). Only used when in Release mode.
- MergeAllJavascriptFiles As Boolean [write only]
Must be set before Build(). Only used when in Release mode.
- MinifyOnline As Boolean [write only]
Using the API of:
https://javascript-minifier.com, the generated Javascript file will be minified
https://cssminifier.com, the CSS files will be minified
- RemoveDeadCode As Boolean [write only]
Only works in Build
The transpiler does not GENERATE dead code (never used). It does NOT remove the B4J code!
Use ShowWarningDeadCode beforehand to check if the transpiler is correct.
Methods with a _ in their name are always considerd to be needed.
- ShowWarningDeadCode As Boolean [write only]
Only works in Build
Shows a warning in the log if the transpiler suspects some code is dead (never used).
This is handy, especially in the final stage of development to remove code (or comment out) that is never used.
Methods with a _ in their name are always considerd to be needed.
You can then use the RemoveDeadCode property to prevent GENERATING dead javascript code.
- UseServiceWorker As Boolean [write only]
Can ONLY be used in AppStart(). Set this param to false if you do not want to use a ServiceWorker
Default true
BANanoURL
Functions:
- CreateObjectUrl (object As Object) As BANanoURL
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter.
The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
To release an object URL, call revokeObjectURL().
- GetField (field As String) As BANanoObject
Gets a field value
- GetHash As String
returns a String containing a '#' followed by the fragment identifier of the URL.
The fragment is not percent-decoded. If the URL does not have a fragment identifier, this property contains an empty string - "".
- GetHost As String
The host property of the URL interface is a String containing the host, that is the hostname, and then,
if the port of the URL is nonempty, a ':', and the port of the URL.
- GetHostname As String
Gets the hostname property of the URL interface is a String containing the domain of the URL.
- GetHref As String
Gets the href property of the URL interface is a String containing the whole URL.
- GetPassword As String
Gets the password property of the URL interface is a String containing the password specified before the domain name.
If it is set without first setting the username property, it silently fails.
- GetPathname As String
Gets the pathname property of the URL interface is a String containing an initial '/' followed by the path of the URL (or the empty string if there is no path).
- GetPort As String
Gets the port property of the URL interface is a String containing the port number of the URL. If the URL does not contain an explicit port number, it will be set to ''.
- GetProtocol As String
Gets the protocol property of the URL interface is a String representing the protocol scheme of the URL, including the final ':'.
- GetSearch As String
Get the search property of the URL interface is a search string, also called a query string, that is a String containing a '?' followed by the parameters of the URL.
Modern browsers provide the URL.searchParams property to make it easy to parse out the parameters from the querystring.
- GetUsername As String
Gets the username property of the URL interface is a String containing the username specified before the domain name.
- Initialize (url As String, base As String)
returns a newly created URL object representing the URL defined by the parameters. *
- Result As Object
Gets the result
- RevokeObjectURL (url As BANanoURL)
The URL.revokeObjectURL() static method releases an existing object URL which was previously created by calling URL.createObjectURL().
Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer.
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- SetField (field As String, value As Object)
Sets a field value
- SetHash (hash As String)
set a '#' followed by the fragment identifier of the URL
- SetHost (host As String)
sets the host property, a String containing the host, that is the hostname, and then,
if the port of the URL is nonempty, a ':', and the port of the URL.
- SetHostname (hostname As String)
Sets the hostname property of the URL interface is a String containing the domain of the URL.
- SetHref (href As String)
Sets the href property of the URL interface is a String containing the whole URL.
- SetPassword (password As String)
Sets the password property of the URL interface is a String containing the password specified before the domain name.
If it is set without first setting the username property, it silently fails.
- SetPathname (pathname As String)
Sets the pathname property of the URL interface is a String containing an initial '/' followed by the path of the URL (or the empty string if there is no path).
- SetPort (port As String)
Sets the port property of the URL interface is a String containing the port number of the URL. If the URL does not contain an explicit port number, it will be set to ''.
- SetProtocol (protocol As String)
Sets the protocol property of the URL interface is a String representing the protocol scheme of the URL, including the final ':'.
- SetSearch (search As String)
Set the search property of the URL interface is a search string, also called a query string, that is a String containing a '?' followed by the parameters of the URL.
Modern browsers provide the URL.searchParams property to make it easy to parse out the parameters from the querystring.
- SetUsername (username As String)
Sets the username property of the URL interface is a String containing the username specified before the domain name.
- ToJSON As String
The toJSON() method of the URL interface returns a String containing a serialized version of the URL, although in practice it seems to have the same effect as URL.toString().
- ToString As String
The URL.toString() stringifier method returns a String containing the whole URL. It is effectively a read-only version of URL.href.
Properties:
- Origin As String [read only]
The origin read-only property of the URL interface returns a String containing the Unicode serialization
of the origin of the represented URL. The exact structure varies depending on the type of URL
- SearchParams As Map [read only]
The searchParams readonly property of the URL interface returns a URLSearchParams object allowing access to the GET decoded query arguments contained in the URL.
BANanoWebSocket
Events:
- OnClose (event As BANanoEvent)
- OnConnecting (event As BANanoEvent)
- OnError (event As BANanoEvent)
- OnMessage (event As BANanoEvent)
- OnOpen (event As BANanoEvent)
- OnServerReady()
- WebSocket_Connected()
- WebSocket_Disconnected (event As BANanoEvent)
Fields:
- CLOSED As Int
- CLOSING As Int
- CONNECTING As Int
- OPEN As Int
Functions:
- B4JSend (methodName As String, data As Map)
Same as send, but for a B4J WebServer. Is send as an event
The methodName MUST end with _BAN and have only one parameter: Params as Map!
e.g. myServerFunc_BAN(Params as Map)
ws.B4JSend("myServerFunc_BAN", CreateMap("Message": "My message"))
- Close
Closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
- CloseReason (code As Int, Reason As String)
Closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
- GetField (field As String) As BANanoObject
Gets a field value
- Initialize (Url As String)
If using BANanoServer. Raises classic B4J WebSocket_Connected and WebSocket_Disconnected events.
Do NOT use if you do not use a BANanoServer! Use InitializeExtended instead.
Creates a new WebSocket using the url (ws:// or wss://).
- InitializeExtended (eventName As String, Url As String, protocols As String, isReconnectingWebSocket As Boolean)
Extended version that raises events _OnOpen, _OnClose, _OnMessage, _OnError, _OnConnecting and _OnServerReady (if using BANanoServer)
Creates a new WebSocket using the url (ws:// or wss://).
protocols: leave empty ("") if not used.
isReconnectingWebSocket: if true, then a special WebSocket will be used which tries to reconnect if the connection is lost
- IsReconnected As Boolean
In case of a Reconnecting Websocket, you can check if this was a reconnected session
- Result As Object
Gets the result
- RunFunction (Function As String, Args As List)
Runs a B4J function. Pass null to Args if is not needed.
- RunFunctionWithResult (Function As String, Args As List) As BANanoPromise
Similar to RunFunction. Returns a BANanoPromise with the result.
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- Send (data As Object)
Enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount
by the number of bytes needed to contain the data. If the data can't be sent (for example, because it needs to be buffered
but the buffer is full), the socket is closed automatically.
- SetField (field As String, value As Object)
Sets a field value
Properties:
- BinaryType As String
CAN NOT BE USED WITH A RECONNECTING WEBSOCKET!
Get/Set the type of binary data being transmitted by the connection.
Possible values "blob" or "arraybuffer"
- BufferedAmount As Long [read only]
CAN NOT BE USED WITH A RECONNECTING WEBSOCKET!
Readonly property returns the number of bytes of data that have been queued using calls to send() but not yet transmitted to the network.
This value resets to zero once all queued data has been sent. This value does not reset to zero when the connection is closed:
if you keep calling send(), this will continue to climb.
- Extensions As String [read only]
CAN NOT BE USED WITH A RECONNECTING WEBSOCKET!
Readonly property returns the extensions selected by the server.
This is currently only the empty string or a list of extensions as negotiated by the connection.
- IsSupported As Boolean [read only]
Check if the browser does support WebSockets
- Protocol As String [read only]
Readonly property returns the name of the sub-protocol the server selected:
this will be one of the strings specified in the protocols parameter when creating the WebSocket object.
- ReadyState As Int [read only]
Readonly property returns the current state of the WebSocket connection.
See the constants on this object.
- ReconnectAttempts As Int [read only]
The number of attempted reconnects since starting, or the last successful connection. Read only.
Only for a Reconnecting WebSocket
- Url As String [read only]
Rreadonly property returns the absolute URL of the WebSocket as resolved by the constructor.
BANanoWindow
Functions:
- AddEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
true - The event handler is executed in the capturing phase
false - The event handler is executed in the bubbling phase
- AddEventListenerOpen (eventName As String, params As Object)
All the code between AddEventListenerOpen and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpen MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpen("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = function(aEvt) {
...
};
- AddEventListenerOpenAsync (eventName As String, params As Object)
All the code between AddEventListenerOpenAsync and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpenAsync MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpenAsync("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = async function(aEvt) {
...
};
- Alert (message As String)
Displays an alert box with a message and an OK button
Same as BANano.Msgbox() or BANano.Alert()
- Atob (base64String As String) As String
Decodes a base-64 encoded string
- Blur
Removes focus from the current window
- Btoa (string As String) As String
Encodes a string in base-64
- CancelAnimationFrame (requestID As Long)
cancels an animation frame request previously scheduled through a call to window.requestAnimationFrame().
- ClearInterval (timerVar As Object)
Clears a timer set with setInterval()
- ClearTimeout (timerVar As Object)
Clears a timer set with setTimeout()
- Close
Closes the current window
- Closed As Boolean
Returns a Boolean value indicating whether a window has been closed or not
- CloseEventListener
Closes an AddEventListenerOpen or AddEventListenerOpenAsync method
- Confirm (message As String) As Boolean
Displays a dialog box with a message and an OK and a Cancel button
- Focus
Sets focus to the current window
- FrameElement As BANanoObject
Returns the iframe element in which the current window is inserted
- Frames As BANanoObject()
Returns all ifram> elements in the current window
- GetField (field As String) As BANanoObject
Gets a field value
- GetName As String
Sets or returns the name of a window
- InnerHeight As Double
Returns the height of the window's content area (viewport) including scrollbars
- InnerWidth As Double
Returns the width of a window's content area (viewport) including scrollbars
- Length As Int
Returns the number of iframe elements in the current window
- MoveBy (x As Double, y As Double)
Moves a window relative to its current position
- MoveTo (x As Double, y As Double)
Moves a window to the specified position
- Open (URL As String, name As String, specs As String, replace As Boolean)
Opens a new browser window
For more info: https://www.w3schools.com/jsref/met_win_open.asp
- Opener As BANanoWindow
Returns a reference to the window that created the window
- OuterHeight As Double
Returns the height of the browser window, including toolbars/scrollbars
- OuterWidth As Double
Returns the width of the browser window, including toolbars/scrollbars
- PageXOffset As Double
Returns the pixels the current document has been scrolled (horizontally) from the upper left corner of the window
- PageYOffset As Double
Returns the pixels the current document has been scrolled (vertically) from the upper left corner of the window
- Parent As BANanoWindow
Returns the parent window of the current window
- Print
Prints the content of the current window
- Prompt (message As String, defaultValue As String) As String
Displays a dialog box that prompts the visitor for input
- RemoveEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
Removes event handlers that have been attached with the addEventListener() method
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies the event phase to remove the event handler from.
true - Removes the event handler from the capturing phase
false - Removes the event handler from the bubbling phase
- RequestAnimationFrame (module As Object, methodName As String) As Long
The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests
that the browser call a specified function to update an animation before the next repaint.
The mathod to call when it's time to update your animation for the next repaint. MUST be defined as:
funcName(timeStamp As double)
- ResizeBy (width As Double, height As Double)
Resizes the window by the specified pixels
- ResizeTo (width As Double, height As Double)
Resizes the window to the specified width and height
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- ScreenLeft As Double
Returns the horizontal coordinate of the window relative to the screen
- ScreenTop As Double
Returns the vertical coordinate of the window relative to the screen
- ScreenX As Double
Returns the horizontal coordinate of the window relative to the screen
- ScreenY As Double
Returns the vertical coordinate of the window relative to the screen
- ScrollBy (x As Double, y As Double)
Scrolls the document by the specified number of pixels
- ScrollTo (x As Double, y As Double)
Scrolls the document to the specified coordinates
- Self As BANanoWindow
Returns the current window
- SetField (field As String, value As Object)
Sets a field value
- SetInterval (callback As Object, ms As Int) As Object
Calls a function or evaluates an expression at specified intervals (in milliseconds)
- SetName (name As String)
Sets or returns the name of a window
- SetTimeout (callback As Object, ms As Int) As Object
Calls a function or evaluates an expression after a specified number of milliseconds
- Stop
Stops the window from loading
- Top As BANanoWindow
Returns the topmost browser window
BANanoXMLHttpRequest
Fields:
- DONE As Int
- HEADERS_RECEIVED As Int
- LOADING As Int
- OPENED As Int
- UNSENT As Int
Functions:
- Abort
Abort the call
- AddEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
true - The event handler is executed in the capturing phase
false - The event handler is executed in the bubbling phase
- AddEventListenerOpen (eventName As String, params As Object)
All the code between AddEventListenerOpen and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpen MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpen("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = function(aEvt) {
...
};
- AddEventListenerOpenAsync (eventName As String, params As Object)
All the code between AddEventListenerOpenAsync and CloseEventListener is transpiled between those lines
eventName: A String that specifies the name of the event. (Do not use the 'on' prefix!)
An AddEventListenerOpenAsync MUST always be closed by an CloseEventListener!
params: params it has to pass in the function() method
req.AddEventListenerOpenAsync("onreadystatechange", aEvt)
...
req.CloseEventListener
transpiles to:
req.onreadystatechange = async function(aEvt) {
...
};
- CloseEventListener
Closes an AddEventListenerOpen or AddEventListenerOpenAsync method
- GetAllResponseHeaders As String
Returns a string containing all header value pairs from the response.
- GetField (field As String) As BANanoObject
Gets a field value
- GetResponseHeader (header As String) As String
Returns the value for the specified header. Returns null if the headers do not contain a value for header.
- GetResponseType As String
Determines the type returned by response:
'' (default) Same as 'text'
'text' String
'arraybuffer' ArrayBuffer
'blob' Blob
'document' Document
'json' Object
- GetTimeout As Double
Gets the timout value
- GetWithCredentials As Boolean
Gets if credentials are used
- Initialize
Creates a new XMLHttpRequest object.
- Open (method As String, url As String)
Specifies the url to read from and the http method ('GET', 'POST', 'PUT', 'DELETE', etc) to use when reading the url.
- Open2 (method As String, url As String, async As Boolean, user As String, password As String)
Specifies the url to read from and the http method ('GET', 'POST', 'PUT', 'DELETE', etc) to use when reading the url.
If async is true, the request will be asynchronous and you should provide an onload callback to be called when the read completes.
In general, it is best to use the asynchronous request so the browser remains responsive while the request is in progress.
- RemoveEventListener (eventName As String, callbackMethod As Object, useCapture As Boolean)
Removes event handlers that have been attached with the addEventListener() method
callbackMethod: Specifies the function to run when the event occurs. Use BANano.CallBackMethod()
useCapture: A Boolean value that specifies the event phase to remove the event handler from.
true - Removes the event handler from the capturing phase
false - Removes the event handler from the bubbling phase
- Result As Object
Gets the result
- RunMethod (methodName As String, params As Object) As BANanoObject
Runs a method on the JavaScript object.
NOTE: the outer Array will be removed in the javascript.
So if you want to pass an array, you have to add an extra array.
e.g. if you want to pass "[0,0], "Alain", you actually have to pass [[0,0], "Alain"]
RunMethod("myMethod", Array(Array(0,0), "Alain"))
If only one, non Array param is passed, you can ignore this.
e.g. this is valid
RunMethod("myMethod", "Alain")
- Send
Sends the request
- Send2 (obj As Object)
Sends the request, The param obj can be a Document, Formdata, Blob, ArrayBuffer or a String
- SetField (field As String, value As Object)
Sets a field value
- SetRequestHeader (header As String, value As String)
sets the value of an HTTP request header. When using setRequestHeader(), you must call it after calling open(), but before calling send().
If this method is called several times with the same header, the values are merged into one single request header.
- SetResponseType (rspType As String)
Determines the type returned by response. Must be set to one of the following:
'' (default) Same as 'text'
'text' String
'arraybuffer' ArrayBuffer
'blob' Blob
'document' Document
'json' Object
Must be set before readyState reaches LOADING.
- SetTimeout (timeoutValue As Double)
Sets the timout value
- SetWithCredentials (withCred As Boolean)
Sets if credentials have to be used
Properties:
- OverrideMimeType As String [write only]
specifies a MIME type other than the one provided by the server to be used instead when interpreting the data being transferred in a request.
This may be used, for example, to force a stream to be treated and parsed as "text/xml", even if the server does not report it as such.
- ReadyState As Int [read only]
The current state of this. Will be one of UNSENT, OPENED, HEADERS_RECEIVED, LOADING, or DONE (see consts).
- Response As Object [read only]
Returns the response from the server in the type specified by responseType. Only valid after the load event fires.
- ResponseText As String [read only]
Returns the response from the server as a string. Only valid after the load event fires and if responseType is set to '' (the default) or 'text'.
- ResponseXML As Object [read only]
returns a Document object
- Status As Int [read only]
The http status code for the request. See statusText for a description of the code.
- StatusText As String [read only]
A description of the status return code.
- Upload As BANanoObject [read only]
Returns aBANanoObject associated with this XMLHttpRequest that can be used to track the upload status of the send() call.