B4J Code Snippet [BANano]: Sharing the goodness

Ola

Thought I should create my own easy reference list of stuff I've posted here about BANano.

Tutorials
BANano for Dummies by Example
BANanoJSONQuery to the rescue: The case of the survey app.
Client Side Excel Report Generation [BANanoOXML]
Exploring BANanoEvents [BANano]
Sending Contact Us Form contents to an email with inline PHP [BANano]
Understanding CRUD logic with ExecuteCallBack [BANanoSQL]
Sharing the goodness [BANano]


Libraries
An Object Oriented UX library for BANano [BANanoWebix]
Got it! - Easy Hints [BANano]
A treeview you might use [BANano]
ChartJS charts with 1 line of code using UOECharts [BANano]
Implementing Collaboration with TogetherJS [BANano]
Implementing LiveHelp for your WebApp [ABMaterial]
Create your UX with MaterializaCSS using UOEBANano
UOEGrid: An interesting grid that you might like [BANano]
UOEGridTable Conditional Value Display Formatting [BANano]
UOEGridTable IconRenderer [BANano]
UOEGrid Column Renderer - Let's display images etc [BANano]
Creating Connected Grid Tables with UOEGridTable [BANano]
Creating Master Details Grid with UOEGridTable [BANano]


BackEnd

A BANanoSQL helper class for CRUD functionality [BANanoSQLUtils]
An inline PHP class for your MySQLI CRUD functionality [BANanoMySQL]
BANanoSQL CRUD-ing around with BANanoSQLUtils [BANano]
Exploring Using PHP & SQLite for your WebApp [BANano]
MySQL CRUD with PHP - Part 1 [BANano]
MySQL CRUD with PHP - Part 2 [BANano]
MySQL CRUD with PHP - Part 3.1 [A look an inline PHP] [BANano]
PDO CRUD Class for MSSQL [BANanoMSSQL]
SQLiteDB PHP CRUD Class for BANano [BANanoSQLite]

Experiments

A Material Design Lite framework for Website / WebApp Creation [BANanoReactMDL]
Beginning 3D with Three.JS [BANano3D]
Beginning HTML5 games with CreateJS [BANanoCreateJS]
Building WebApps/Websites with VueJS [BANanoVue]
15 Mockup Elements for your Prototypes [BANAnoWired]
Create reactive, state based components & UI [BANanoReef]
Creating a CRUD app with LocalStorage Backend [BANano]
Creating a hotel reservation app with BANanoJQM
Creating the PhotoNinja Website with UOE [Websites]
CRUD with grid & modal using UOENow [BANanoSQL]
Distributing and accessing an existing SQLite Databases - Part 1 [BANano]
A tabbed dialog to Login, Register, Forgot Password & Reset Password [BANano]
Let's please build a Community Project [BANanoReact]
Executing code without using BANano.Eval [BANano]


Questions
Question:
[SOLVED] Extending Event Driven BANanoSQL with own CallBacks?
Question: [SOLVED] How to maintain element events?
Question: [SOLVED] How to set BANanoEvent Bubbling Off?
Question: [SOLVED] BANanoMaterial Error Fix
Question: [SOLVED] How can I run a JavaScript Method and wait for it to finish?
Question: [SOLVED] Returning all list items in For Each
Question: [SOLVED] How does one use Header.AddMeta?
Question: [SOLVED] How to turn minify off/on
Question: [SOLVED] Empty string passed to getElementID('')
Question: [SOLVED] How to find element existence
Question: [SOLVED] How to CallSub inside #If JavaScript
Question: [SOLVED] Library Compilation FileNotFound Exception
Question: [SOLVED] Map.Initialize inclusion of map keys
Question: [SOLVED] How to transvese elements by name and return attributes
Question: [SOLVED] How to call different subs for different elements
Question: [SOLVED] RangeError: Maximum Stacktrace exceeded
Question: [SOLVED] How do I refresh a page
Question: [SOLVED] FloatingActionButton iif method not defined
Question: [SOLVED] Enumeration Initialization Assignments
Question: [SOLVED] Else If Transpiling Error
Question: [SOLVED] Map Object Enhancements
Question: [SOLVED] Support for String()
Question: [SOLVED] Using / Converting Own B4J Classes
Question: [SOLVED] Ajax Calls: How to convert B4J Http Calls

To relook at these *unresolved

Question:
How to embed & read a json file / rather use BANanoSQL to load it?
Question: How can I upload a file using Php?
Question: CRUD bug using wait
Question: Using MySQL / MSSQL with PHP
Question: How to add dynamic css / injectcss to my app
Question: How to AddJavascriptFile and AddCSSFile on demand

Now for some code snippets...

Removing Attributes

One of the elusive attributes is the 'disabled' attributes for elements. Apparently whether you set this to true/false to enable your element, the status quo stays the same. It seems the only way to toggle this is to remove it to enable your element.

The code snippet here is to remove attributes from elements.

B4X:
'remove an attribute
Sub removeAttr(elID As String, attrName As String)
    elID = elID.tolowercase
    Dim jQ As BANanoObject
    jQ.Initialize("$")
    jQ.Selector($"#${elID}"$).RunMethod("removeAttr", Array(attrName))
End Sub

#Tested

Update: 30 Jan 2019

A new method to remove attribute has been added as BANano.BANanoElement.RemoveAttr
 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
For Loops

The For Each Loop (the variable type on the loop should be defined)

B4X:
write("For Each Loop<br /> ")
    Dim appNames() As String = Array("b4a", "b4i", "b4j", "b4r")
    For Each appName As String In appNames
        write(appName)
        write("<br />")
    Next
    write ("Exiting from the loop!")

Output

1600799707737.png


The Counter Loop

B4X:
write("Counter For Loop<br /> ")
    '
    Dim x As Int = 10
    Dim y As Int
    For y = 1 To x
        write($"y: ${y}"$)
        write("<br />")
   Next
    write ("Exiting counter loop!")

Output

1600799831333.png


The Step Down Loop

B4X:
Dim x As Int = 10
    Dim y As Int
    For y = 10 To 1 Step -1
        write($"y: ${y}"$)
        write("<br />")
    Next
    write ("Exiting step counter loop!")

1600799906031.png
 

Mashiane

Expert
Licensed User
Longtime User
Exiting & Skipping Loops

This is based on a condition

1. Here we exit as soon as the counter is 5

B4X:
write("Starting Do Loop ")
        
    Do Until (count = 10)
        write($"Current Count : ${count}<br />"$)
        count = count + 1
        '*****
        If count = 5 Then Exit
    Loop
   
    write("Loop stopped!")

Output

1600800283080.png


2. Here we skip and process the next loop line as soon as the item is 6

B4X:
Dim b As Int = 0
    For b = 1 To 10
        If b = 6 Then
            Continue
        End If
        document.write($"Item: ${b}</br>"$)   
    Next

output

1600800757488.png
 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
A helper class to add a BANanoElement in any parent element.

B4X:
Sub AddElement(parentID As String, tag As String, id As String) As BANanoElement
    Dim el As BANanoElement = BANano.GetElement($"#${parentID}"$).Append($"<${tag} id="${id}"></${tag}>"$).Get($"#${id}"$)
    Return el
End Sub

Usage

B4X:
AddElement("body", "h1", "myh1").SetText("h1. Neumorphism UI heading")

Meaning:

Find the #body element, append to it a h1 element, set the id of the newly created h1 element to myh1, then set the text to "h1. Neomorphism UI heading


1601822944919.png
 

Mashiane

Expert
Licensed User
Longtime User
RunRecursive

B4X:
'run a recursive method
Sub RunRecursive(data As Map, path As String) As Object
    Dim prevObj As BANanoObject = data
    Dim items As List = BANano.Split(".", path)
    Dim iTot As Int = items.Size
    Dim iCnt As Int
    '
    Dim strprev As String = ""
    Dim prtObj As BANanoObject
    Dim litem As String = items.Get(iTot - 1)
    '
    For iCnt = 1 To iTot - 1
        'get the previos path
        strprev = items.Get(iCnt - 1)
        'the parent object
        prtObj = prevObj.GetField(strprev)
        'this does not exist, return
        If BANano.IsUndefined(prtObj) Then
            Return Null
        Else
            prevObj = prtObj
        End If
    Next
    Dim res As Object = prevObj.RunMethod(litem, Null).Result
    If BANano.IsUndefined(res) Then
        res = Null
    End If
    Return res
End Sub

Example code.. this executes a .RunMethod on the last path element delimited by .

Example Code

B4X:
Dim lat As Double = BANanoShared.RunRecursive(place, "geometry.location.lat")
    Dim lng As Double = BANanoShared.RunRecursive(place, "geometry.location.lng")

Ta!
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
#if javascript
function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}
#End If

'convert a dataURI to blob for form data
Sub dataURItoBlob(sDataURI As String) As BANanoObject
    Dim out As BANanoObject = BANano.RunJavascriptMethod("dataURItoBlob", Array(sDataURI))
    Return out
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
Hex to RGB and back

B4X:
#if javascript
function rgbToHex(r, g, b) {
  return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if(result){
      var r= parseInt(result[1], 16);
      var g= parseInt(result[2], 16);
      var b= parseInt(result[3], 16);
      return r+","+g+","+b;//return 23,14,45 -> reformat if needed 
  } 
  return null;
}
#End If

'convert RGB to HEX
Sub RGBToHex(r As Int, g As Int, b As String) As String
    Dim sout As String = BANano.RunJavascriptMethod("rgbToHex", Array(r, g, b))
    Return sout    
End Sub

'convert HEX to RGB
Sub HexToRGB(hexValue As String) As String
    Dim sout As String = BANano.RunJavascriptMethod("hexToRgb", Array(hexValue))
    Return sout    
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
'build URLSearchParams from a Map (used with BANanoFetch)

B4X:
Sub URLSearchParamsFromMap(params As Map) As BANanoObject
    Dim obj As BANanoObject
    obj.Initialize2("URLSearchParams", params)
    Return obj
End Sub

build a URLQueryString from Map

B4X:
Sub URLQueryStringFromMap(params As Map) As String
    Dim sb As StringBuilder
    sb.Initialize 
    For Each k As String In params.Keys
        Dim v As String = params.Get(k)
        k = banano.EncodeURIComponent(k)
        v = banano.EncodeURIComponent(v)
        sb.Append($"${k}=${v}&"$)
    Next
    Dim sout As String = sb.ToString
    sout = BANanoShared.RemDelim(sout, "&")
    Return sout
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
'Showing browser notifications...

B4X:
'show the browser notification
Sub ShowBrowserNotification(Title As String, Desc As String, Url As String, Icon As String, Vibrate As Boolean, Seconds As Int)        'ignoreDeadCode
    'get the notification oject
    Dim notif As BANanoObject = BANano.Window.GetField("Notification")
    'check the permission
    Dim permission As String = notif.GetField("permission").Result
    If permission <> "granted" Then
        'requestPermission
        Dim resp As String = BANano.Await(notif.RunMethod("requestPermission", Null))
        If resp <> "granted" Then Return
    End If
    
    Dim Options As Map = CreateMap()
    Options.Put("icon", Icon)
    Options.Put("body", Desc)
    Options.Put("vibrate", Vibrate)
    '
    Dim n As BANanoObject
    n.Initialize2("Notification", Array(Title, Options))
    Dim showEvent As String = "notification_show"
    Dim closeEvent As String = "notification_close"
    Dim errorEvent As String = "notification_error"
    Dim clickEvent As String = "notification_click"
    
    If SubExists(EventHandler, showEvent) Then
        n.AddEventListener("show", BANano.CallBack(EventHandler, showEvent, Null), False)
    End If
    If SubExists(EventHandler, clickEvent) Then
        n.AddEventListener("click", BANano.CallBack(EventHandler, clickEvent, Null), False)
    End If
    If SubExists(EventHandler, errorEvent) Then
        n.AddEventListener("error", BANano.CallBack(EventHandler, errorEvent, Null), False)
    End If
    If SubExists(EventHandler, closeEvent) Then
        n.AddEventListener("close", BANano.CallBack(EventHandler, closeEvent, Null), False)
    End If
    'close after
    Dim cbClose As BANanoObject = BANano.callback(Me, "CloseNotification", Array(n))
    Dim Sec As Int = Seconds * 1000
    BANano.Window.SetTimeout(cbClose, Sec)
End Sub


private Sub CloseNotification(n As BANanoObject)            'ignoreDeadCode
    n.RunMethod("close", Null)
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
Table Pagination Script in JavaScript

B4X:
"use strict";

var paginate = function paginate(items) {
  var page = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  var perPage = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
  var offset = perPage * (page - 1);
  var totalPages = Math.ceil(items.length / perPage);
  var paginatedItems = items.slice(offset, perPage * page);
  return {
    previousPage: page - 1 ? page - 1 : null,
    nextPage: totalPages > page ? page + 1 : null,
    total: items.length,
    totalPages: totalPages,
    items: paginatedItems
  };
};
 

Mashiane

Expert
Licensed User
Longtime User
I needed code to remove an item from a select HTML5 element by value.

Here is what worked for me... (the banano way)

B4X:
Sub removeByValue(value As String)
    'get the options of the select
    Dim xOptions As Object = mElement.GetField("options")
    'convert the HTMLCollection to array
    Dim a As BANanoObject
    a.Initialize("Array")
    Dim aOptions As List = a.RunMethod("from", xOptions)
    'find the size of the array
    Dim aTot As Int = aOptions.Size - 1
    Dim aCnt As Int = 0
    For aCnt = 0 To aTot
        'get each option
        Dim optionx As BANanoObject = aOptions.Get(aCnt)
        'get the value
        Dim k As String = optionx.GetField("value").Result
        'if the value matches remove the item
        If k.EqualsIgnoreCase(value) Then
            mElement.RunMethod("remove", aCnt)
        End If
    Next
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
I needed a way to find an Index of an item in a select HTML element by value, the BANano way...

B4X:
Sub findIndexByValue(value As String) As Int
    'get the options of the select
    Dim xOptions As Object = mElement.GetField("options")
    'convert the HTMLCollection to array
    Dim a As BANanoObject
    a.Initialize("Array")
    Dim aOptions As List = a.RunMethod("from", xOptions)
    'find the size of the array
    Dim aTot As Int = aOptions.Size - 1
    Dim aCnt As Int = 0
    For aCnt = 0 To aTot
        'get each option
        Dim optionx As BANanoObject = aOptions.Get(aCnt)
        'get the value
        Dim k As String = optionx.GetField("value").Result
        'if the value matches return the index
        If k.EqualsIgnoreCase(value) Then
            Return aCnt
        End If
    Next
    'the item is not found
    Return -1
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
Get the HTML inside a <template> tag item.

Use <template> to hold some content that will be hidden when the page loads.

B4X:
'get the content of a template
Sub getTemplate As String
    Dim clon As BANanoObject = mElement.RunMethod("cloneNode", True)
    Dim fc As String = clon.GetField("firstElementChild").GetField("outerHTML").result
    Return fc
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
Ensure that BANano.GetFile??? always retrieves the last updated resource bypassing the cache.

I just picked up that this kind of call sometimes uses the cached content of the file you want to read from assets or otherwise. To ensure that one is able to get the latest content just append "?" & DateTime.Now to the url.

B4X:
Dim fileContents As Map = banano.Await(banano.GetFileAsJSON(strComp & "?" & DateTime.now, Null))

Now things work like a charm.
 
Top