UB

UB

The UB namespace (global object) encapsulates all classes, singletons, and utility methods provided by UnityBase for build a transport layer for a Web applications.

The main entry point for most operation is UBConnection for communication with UnityBase server.

Author:
  • pavel.mash

Members

userAgent: String static

isChrome: Boolean static

isWebKit: Boolean static

isGecko: Boolean static

isOpera: Boolean static

isMac: Boolean static

isSecureBrowser: Boolean static

appConfig static

Properties:
Name Type Description
appConfig Object

UnityBase application parameter. All this parameters can be configured in ubConfig.uiSettings.adminUI section of application configuration file.

Properties
Name Type Description
applicationName String

Name of current application. This text shown in the left side of main window toolbar in Ext-based web client

loginWindowTopLogoURL String
loginWindowBottomLogoURL String
defaultLang String

Default application language

supportedLanguages Array.<String>

Array of all languages supported by application.

defaultPasswordForDebugOnly String

Fill password on login window. Set this parameter for debug purpose only!

comboPageSize Number

Page size of UBCombobox drop-down (in case !disablePaging)

maxMainWindowTabOpened Number

How many tab user can open in the same time in the main workspace

storeDefaultPageSize Number

Default page size of UnityBase store

gridHeightDefault Number

Default height of grid in form

gridWidthDefault Number

Default width of grid in form

gridParentChangeEventTimeout Number

Timeout for fire parentchange event

gridDefaultDetailViewHeight Number

Default height of detail grid and preview form inside master grid

formMinHeight Number

Minimum form height

formMinWidth Number

Minimum form width

formDefaultAutoFormWidth Number

Default width of auto-generated form

formSaveMaskDelay Number

How long (in ms) wait before mask form while save action call. Usually save if quick operation and we do not need mask form at all

scanRecognizeProgressInterval Number

Callback call interval while do scan recognition using UBDesktopService extension

browserExtensionNMHostAppKey String

Native messages plugin application key

onError: UB-onError static

onError handler. If set - this one is call, otherwise - default handler will be called

onShowLoginWindow static

Handler, called by login method. This handler must show login window and call callback with parameter: { authSchema: authSchemaUserChoose, login: loginNameUserInput, pwd: passwordUserInput, callback: Function(result)} after user confirm Login. After do authentication UB call callback with object {success: Boolean, errMsg: String} Login window can use data from UB.appConfig - it is initialized before login call
Properties:
Type Description
function

xhrDefaults static

The default HTTP parameters for UB.xhr
Properties:
Name Type Description
xhrDefaults Object
Properties
Name Type Description
transformRequest Array.<function()>

request transformations

transformResponse Array.<function()>

response transformations

headers Object

Default headers to apply to request (depending of method)

timeout Number

Default timeout to apply to request

interceptors: Array.<Object> protected static

Interceptors array

pendingRequests: Array.<Object> protected static

Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes.

Methods

apply(objectTo, …objectsFrom)Object static

Copies all the properties of one or several objectsFrom to the specified objectTo. Non-simple type copied by reference!
Arguments:
  1. objectTo (Object)  The receiver of the properties
  2. ...objectsFrom (Object)  The source(s) of the properties

format(stringToFormat, …values)String static

Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each token must be unique, and must increment in the format {0}, {1}, etc. Example usage:

var s = UB.format('{1}/ext-lang-{0}.js', 'en', 'locale');
// s now contains the string: ''locale/ext-lang-en.js''
Arguments:
  1. stringToFormat (String)  The string to be formatted.
  2. ...values (*)  The values to replace tokens {0}, {1}, etc in order.

ns(namespacePath)Object static

Creates namespaces to be used for scoping variables and classes so that they are not global.
Arguments:
  1. namespacePath (String)
Example
UB.ns('DOC.Report');

    DOC.Report.myReport = function() { ... };

iso8601Parse(value)Date static

Convert UnityBase server dateTime response to Date object
Arguments:
  1. value

iso8601ParseAsDate(value)Date static

Convert UnityBase server date response to Date object. date response is a day with 00 time (2015-07-17T00:00Z), to get a real date we must add current timezone shift
Arguments:
  1. value

booleanParse(v)Boolean|null static

Convert UnityBase server Boolean response to Boolean (0 = false & 1 = trhe)
Arguments:
  1. v   Value to convert

i18n(localeString) → * static

Return locale-specific resource from it identifier. localeString must be previously defideb dy call to UB#i18nExtend
Arguments:
  1. localeString (String)

i18nExtend(localizationObject) static

Merge localizationObject to UB.i18n. Usually called form modelPublic/locale/lang-*.js scripts
Arguments:
  1. localizationObject (Object)

base64FromAny(data) → Promise static

Fast async transformation of data to base64 string
Arguments:
  1. data (File|ArrayBuffer|String|Blob|Array)

base64toArrayBuffer(base64)ArrayBuffer static

Convert base54 encoded string to decoded array buffer
Arguments:
  1. base64 (String)

log(…msg) static

Log message to console (if console available)
Arguments:
  1. ...msg (*)

logError(…msg) static

Log error message to console (if console available)
Arguments:
  1. ...msg (*)

logWarn(…msg) static

Log warning message to console (if console available)
Arguments:
  1. ...msg (*)

logDebug(…msg) static

Log debug message to console. Since it binded to console, can also be used to debug Promise resolving in this way:

 UB.get('timeStamp').done(UB.logDebug);
Arguments:
  1. ...msg (*)

doOnProcessError(errMsg, errCodeopt)function static

Arguments:
  1. errMsg (String)
  2. [errCode] (Number)

getResourceVersion(uri)String static

Search for resource version in the window.__ubVersion global const IF any, return 'ver=version' else ''
Arguments:
  1. uri (String)

addResourceVersion(uri)String static

Exec UB.getResourceVersion and if any - add ?ver to resource and return resource with ?ver
Arguments:
  1. uri (String)

inject(url, charsetopt) → Promise static

Inject external script or css to DOM and return a promise to be resolved when script is loaded.

Implement single load mode (if script successfully loaded using UB.inject it not loaded anymore.

Arguments:
  1. url (String)  either js or css resource to load
  2. [charset] (String)
Example
//Load script.js:
      UB.inject('jslibs/script.js').done();

      //Load several script at once and error handling:
      Q.all([UB.inject('jslibs/script.js'), UB.inject('script2.js')])
        .fail(function(err){
           console.log('Oh! error occurred: ' + err) ;
        });

      //Load one script and then load other
      UB.inject('jslibs/js_beautify.js')
       .then(function(){
           console.log('first script loaded. Continue to load second');
           return UB.inject('jslibs/js_beautify1.js');
       }).done();

       //Load couple of resources:
      Q.all([UB.inject('css/first.css'), UB.inject('css/second.css')]).done();

xhr(requestConfig) → Promise static

Promise of perform an asynchronous HTTP request Returns a promise object with the standard Promise methods (reference). The then method takes two arguments a success and an error callback which will be called with a response object. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions. Default transform check response content-type is application/json and if so - convert data to Object
  • status{number} – HTTP status code of the response.
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request.
Arguments:
  1. requestConfig (Object)  Object describing the request to be made and how it should be processed. The object has following properties:
    Properties
    1. url (String)  Absolute or relative URL of the resource that is being requested
    2. [method] (String)  HTTP method (e.g. 'GET', 'POST', etc). Default is GET
    3. [params] (Object.<(string|Object)>)  Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified
    4. [data] (String|Object)  Data to be sent as the request message data
    5. [headers] (Object)  Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Merged with UB.xhrDefaults.headers
    6. [transformRequest] (function|Array.<function(data, function())>)  Transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.
    7. [transformResponse] (function|Array.<function(data, function())>)  Transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
    8. [timeout] (Number|Promise)  timeout in milliseconds, or promise that should abort the request when resolved. Default to {UB.xhrDefaults.timeout}
    9. [withCredentials] (Boolean)  whether to to set the withCredentials flag on the XHR object. See requests with credentials for more information.
    10. [responseType] (String)  see responseType.
Example
//Get some data from server:
     UB.xhr({url: 'getAppInfo'}).done(function(resp) {
         console.log('this is appInfo: %o', resp.data)
     });

     //The same, but in more short form via UB.get shorthand:
     UB.get('getAppInfo').done(function(resp) {
         console.log('this is appInfo: %o', resp.data)
     });

     //Run POST method:
     UB.post('ubql', [
         {entity: 'uba_user', method: 'select', fieldList: ['*']}
     ]).then(function(resp) {
         console.log('success!');
     }, function(resp) {
         console.log('request failed with status' + resp.status);
     });

     //retrieve binary data as ArrayBuffer
     UB.get('downloads/cert/ACSK(old).cer', {responseType: 'arraybuffer'})
     .done(function(res){
         console.log('Got Arrray of %d length', res.data.byteLength);
     });

get(url, configopt) → Promise static

Shortcut for UB.xhr to perform a GET request.
Arguments:
  1. url (string)  Relative or absolute URL specifying the destination of the request
  2. [config] (Object)  Optional configuration object as in UB.xhr

post(url, data, configopt) → Promise static

Shortcut for UB.xhr to perform a POST request.
Arguments:
  1. url (string)  Relative or absolute URL specifying the destination of the request
  2. data (*)  Request content
  3. [config] (Object)  Optional configuration object as in UB.xhr

put(url, data, configopt) → Promise static

Shortcut for UB.xhr to perform a PUT request.
Arguments:
  1. url (string)  Relative or absolute URL specifying the destination of the request
  2. data (*)  Request content
  3. [config] (Object)  Optional configuration object as in UB.xhr

patch(url, data, configopt) → Promise static

Shortcut for UB.xhr to perform a PATCH request.
Arguments:
  1. url (string)  Relative or absolute URL specifying the destination of the request
  2. data (*)  Request content
  3. [config] (Object)  Optional configuration object as in UB.xhr

UBError(message, detailopt, codeopt) static

UnityBase client-side exception. Such exceptions are will not be showed as unknown error in UB#showErrorWindow

message Can be either localized message or locale identifier - in this case UB#showErrorWindow translate message using UB#i18n

Arguments:
  1. message (String)  Message
  2. [detail] (String)  Error details
  3. [code] (Number)  Error code (for server-side errors)
Example
throw new UB.UBError('lockedBy'); // will show message box "Record was locked by other user. It\'s read-only for you now"

UBAbortError(messageopt, detailopt) static

UnityBase still error. Global error handler does not show this error for user. Use it for still reject promise.
Arguments:
  1. [message] (String)  Message
  2. [detail] (String)  Error details

Repository(entityName)ClientRepository static

Construct new ClientRepository object using Core.connection as connection parameter value.

Warning - method added after UBCore.initialize() is resolved.

Arguments:
  1. entityName (String)