Javascript library

iKnowBase provides a javascript-library in the client page. For the most part, the content of this is private for the various components. However, for components in the page engine there is one feature that might be useful.

The objects, methods and properties in the iKnowBase javascript library are generally not intended for manual use, and they will change between versions. However, as far as possible, the items specified in this document will remain backwards compatible.

Global objects

These are the global (top level) objects available to HTML clients, provided automatically by iKnowBase.

Object Description Type
iKnowBase The iKnowBase javascript root object iKnowBase

iKnowBase root object

This object contains functions and properties relating to the entire iKnowBase application.

Property Description Type(s)
PageEngine This property contains the PageEngine object, with methods to refresh page components. PageEngine
busyIndicator This method will run a given function and show a busy indicator while the function runs. Function
notify This method will show a notification to the end user. Function

busyIndicator

The busyIndicator method on the iKnowBase-object will run the given function and show a busy indicator while the function runs. It can apply to either a whole page or a given component.

Parameters

Parameter Description Type
options Can be either a function to be started by the busy indicator, or a hash (object) with properties, as described in the table below. Function/Object

The hash parameter supports the following properties:

Properties Description Type
autoClose If true the busy indicator will close automatically, else closing the busy indicator must be handled manually. Defaults to: true. Boolean
parent If specified the busy indicator will display for the given component, else it will display for the body. It can be specified as a jQuery selector, element, HTML string, or jQuery object. String/Object
start Specifies the function to be started by the busy indicator. Note: This is a required property. Function
text Specifies the text to display with the busy indicator. String

Methods

Method Description
close Closes the busy indicator.

Example

The following function will show the busy indicator while loading css and scripts. It is manually closed in the start-function’s callback.

IKB.ensure = function(data, callback) {
    iKnowBase.busyIndicator({autoClose: false, start: function() {
        var busy = this;
        load($.makeArray(data.js), $.makeArray(data.css), data.wait, function() {
            busy.close();
            callback();
        });
    }});
}

notify

The notify method on the iKnowBase-object will show a notification to the user. It can be of type error, warning, or information. The notification will close when the user clicks on it.

Parameters

Parameter Description Type
options A hash (object) with properties, as described in the table below. Object

The hash parameter supports the following properties:

Properties Description Type
duration Specifies the number of milliseconds to show the notification. It not specified, the notification will remain open until it is manually closed. Number
text Specifies the text/description. String
title Specifies the title. String
type Specifies the type of notification. Supported values: ‘error’, ‘info’, and ‘warning’. String

Methods

Method Description
close Closes the notification.

Example

The following code will show a notification of type information to the user. It will close automatically after 3 seconds.

iKnowBase.notify({
    type:'info',
	  title:'Shows both info-icon, title, and text',
	  text:'Will automatically close after 3 seconds',
	  duration:3000
});

iKnowBase.PageEngine

This object contains functions and properties relating to the page engine.

Property Description Type(s)
reloadComponent This method will reload a component on a page, optionally passing in a set of URL parameters to use during the reload. Function

reloadComponent

The reloadComponent method on the PageEngine-object will reload the specified page component from the server, using a number of different settings. The basic syntax is “iKnowBase.PageEngine.reloadComponent (settings)”, where settings is a javascript hash containing the required settings and parameters, but there are also two old-style supported syntaxes:

It is possible to pass a set of URL-parameters for use during the reload. Whether URL-parameters are required or not, and what various parameters mean, will depend entirely on the (user defined) configuration of the specified page component.

Syntax and parameters

The basic syntax is “iKnowBase.PageEngine.reloadComponent (settings)”, where settings is a javascript hash containing the required settings and parameters. The settings object supports the following properties:

Parameter Description Type
pageComponent The client-side ID of the component to reload, or a jQuery-object pointing to the component String, Element or jQuery
busyIndicator Whether to show a busy indicator during the reload. Defaults to false. Boolean
refreshCache Whether to refresh any current cached content, overriding cache timeouts. Defaults to false. Boolean
updateHtml Whether to update the html of the component, or just load data. Defaults to true. Boolean
errorPopup Whether to automatically display errors, or ignore them. Defaults to true. Boolean
data A hash (object) with URL-parameters to be used during reload hash

The return value from the reloadComponent is a jQuery promise object (actually a jqXHR object) making it possible to attach callbacks using methods such as done(), fail() and always(). See the example below for more information.

Note: In order to use updateHtml, the containing page region must be rendered with decorations, as specified by the page.regions FreeMarker model.

The ID of a page component is automatically and computed by the page engine, using an algorithm that may change between versions. You should generate the component ID during component rendering, using the ComponentModel expression ${component.id}. However, you may also specify the pageComponent ID in the page components tab in iKnowBase Development Studio.

The following example reloads the value of a single component, using the parameter p_document_id=1234:

iKnowBase.PageEngine.reloadComponent ({
    pageComponent: '${component.id}',
    data: {
        p_document_id: 1234
    }
});

The following example adds the busy indicator during reload and ensures that the page component content is regenerated (and not loaded from cache):

iKnowBase.PageEngine.reloadComponent ({
    pageComponent: '${component.id}',
    busyIndicator: true,
    refreshCache:  true,
    data: {
        p_document_id: 1234
    }
});

The following example turns off automatic display of errors, and uses the callbacks done and fail for visual status notifications:

iKnowBase.PageEngine.reloadComponent ({
    pageComponent: id,
    errorPopup: false
}).done (function (data, textStatus, jqXHR) {
    jQuery("#" + id).css("background-color", "green");
}).fail (function (jqXHR, textStatus, errorThrown) {
    jQuery("#" + id).css("background-color", "red");
});

Finding the id of the page component

The ID of a page component is normally computed by the page engine, using an algorithm that may change between versions. You should generate the component ID during component rendering, using the FreeMarker expression ${component.id}. You may also specify a stable pageComponent ID in the page components tab in iKnowBase Development Studio, but you are then responsible for ensuring that there are no conflicts.

Use the following template in a ContentViewer to create a function that will reload the viewer with new data:

<script type="text/javascript">
    function showDocument (docid) {
        iKnowBase.PageEngine.reloadComponent ({
            pageComponent: '${component.id}',
            data: {
                p_document_id: docid
            }
        });
    }
</script>
<h2> ${viewer.data.title}</h2>

Deprecated syntax and parameters

reloadComponent still supports a less versatile syntax “iKnowBase.PageEngine.reloadComponent (pageComponent [, url] [, urlParameters]”. The traditional syntax has both url and urlParameters as optional function parameters, and it will automatically detect if they are present.

Parameter Description Type
pageComponent The client-side ID of the component to reload, or a jQuery-object pointing to the component String, Element or jQuery
url URL to the page to reload from, possibly including URL-parameters String
urlParameters A hash (object) with additional URL-parameters to be used during reload hash

Note that reloadComponent requires that the containing component has been rendered with decorations, as specified by the page.regions FreeMarker model.

iKnowBase.PageEngine.InstantContentCache

This object contains functions and properties relating to the InstantContentCache, i.e. the mechanism that enables clients to receive notification when content caches have been updated. (Note that for this to work, the content cache key must have “publish updates to instant” enabled).

Property Description Type(s)
start This method will start listening for cache notifications, automatically reloading any component which is present on the page Function

start

The reloadComponent method on the PageEngine.InstantContentCache-object will start listening for cache notifications. Before starting, it will check whether it has any page components with known cache keys; if there are none, the listening process witll not start. Whenever a notification is received, it will check whether a component with that particular cache key is known on the page; if it is, it will use PageEngine.reloadComponent to update the data.

Syntax and parameters

The basic syntax is “iKnowBase.PageEngine.InstantContentCache.start (settings)”, where settings is a javascript hash containing the required settings and parameters. The settings object is currently undocumented:

Parameter Description Type
reloadComponent The function to be called to reload a component. Parameters to this function is a hash containing only the attribute pageComponent. If the function is not specified, iKnowBase.PageEngine.reloadComponent will be used. Function

The following example will start listening to cache update notifications, using a default reloadComponent:

iKnowBase.PageEngine.InstantContentCache.start();

The following example will start listening to cache update notifications, telling the user that the page might need to be refreshed:

iKnowBase.PageEngine.InstantContentCache.start({
    reloadComponent: function (settings) {
        iKnowBase.notify ({ text:'Content has been updated. Please refresh the page.' });
    }
});

iKnowBase.Instant

The iKnowBase.Instant object contains functions related to the use of iKnowBase Instant, the component providing real time asynchronous messaging to iKnowBase. Some of the available options are in a sub-object named Atmosphere, so named to indicate that these rely on implementation details of the underlying Atmosphere framework.

For simple usage scenarios, the examples below and in the Development Guide may be sufficient; for more advanced usages you may want to consult and understand the underlying Atmosphere APIs.

Property Description Type(s)
Atmosphere.subscribe Subscribes to a topic, and returns the Atmosphere channel. Function
Atmosphere.publish Publishes a message to an already subscribed channel. Function
Atmosphere.unsubscribe Unsubscribes from a channel already _subscribe_d to. Function
Atmosphere.requestUserListUpdate For userList topics: Request a userList response from the server. Same as subscription option subscribeUserListChanges, but used on demand. Function
Atmosphere.requestUserList For userList topics: Request a filtered userList response from the server. Function
Atmosphere.requestSubscribeUserListChanges For userList topics: enable or disable join/leave updates for the active connection. Same as subscription option subscribeUserListChanges, but used on demand. Function
setDefaultOptions Sets default options to be used for all future subscribe-calls. Function

Atmosphere.subscribe

This method establishes a topic-specific channel between the client and a server. The method also sets up callbacks for various events.

Syntax

iKnowBase.Instant.Atmosphere.subscribe (options)
Parameter Description Type
options Options to be used, a combination of iKnowBase- and Atmosphere specific options. Hash

Options

The options are as follows:

Parameter Description Type
topicName The full name of the topic you want to connect to. String
servletURL CORS only: URL to Instant servlet. Used in conjunction with enableXDR atmosphere option. String
subscriptionOptions iKnowBase-specific options that apply to the subscription. Optional. Hash
atmosphereOptions Atmosphere-specific options that apply to the subscription. Optional. Hash

The subscriptionOptions are as follows:

Parameter Description Type
requestUserList Request that the server provides a full list of subscribed users as soon as the client has connected. Optional. Boolean
subscribeUserListChanges Request that the server provides join and leave messages when users subscribe and unsubscribe to the topic. Optional. Boolean

The atmoshpereOptions are better described in the Atmosphere documentation, but below are the most important.

Parameter Description Type
transport Name of transport to use; Legal values are ‘websocket’ and ‘long-polling’; defaults to ‘long-polling’. String
fallbackTransport Name of transport to use if the preferred transport is unavailable (or fails); defaults to ‘long-polling’. Hash
enableXDR CORS only: Enable CORS communication. Used in conjunction with servletURL option. String
onMessage Callback for when a messsage is received. Receives a single “data” parameter, whose format depends on the topic setup. Function
onOpen Callbacks for when the channel is opened. Function
onClose Callbacks for when the channel is closed. Function
onReconnect Callback for when the client reconnects to the server. Function
onReopen Callback for when a re-connection successfully reconnected. Function
onError Callback for when the client discovers an error. Function
onMessagePublished Callback for when using polling and a response was sent back by the server. Function
onTransportFailure Callback for when the transport fails because it is not supported by the client or the server. Function

Topic name and topic options

The topicName option consists of a topic base name and a set of optional topic options. The combination will uniquely identify a specific topic.

The topic base name is required to start with a “/” (forward slash) and can otherwise only contain alphanumeric characters [a-z|A-Z|0-9] and additional forward slashes. The name is case sensitive.

The topic options are added to the topic base name as URL parameters:

Parameter Value Description
messageFormat TEXT Use simple text message format when publishing and consuming on the topic. This is the default if messageFormat is not set.
messageFormat IKB Use IKB message format when publishing and consuming on the topic.
userList true Enable userList support. Requires messageFormat=IKB. Instant will keep a list of all connected users and support subscriptionOptions requestUserList and subscribeUserListChanges.

While the TEXT message format can be used to send any text information, the IKB message format has additional application support:

Publishers should send messages using a IKBRequestMessage:

Parameter Description Type
toUserName The userName of a the recipient. The message will only be delivered to connections with that userName. Optional. String
messageType A message type identifier the clients can use to describe the message data payload or reason for message. Optional. String
correlationId A optional user specific identifier that can be used with server requests (iKnowBase.Instant.Atmosphere.request*). The identifier will be present in the corresponding response. String
data The data to be sent. Required. String

Note: Publishers can also choose to send a simple text message to a topic with messageFormat=IKB. This message will be set as data and all optional fields will be empty.

Consumers will always receive messages as a IKBResponseMessage:

Parameter Description Type
fromUser The UserReference object of the sender. Present if the user was authenticated, otherwise null. Hash
toUserName The userName of a the recipient. The recipient can see if this was a private message or a public message. Optional. String
messageType A message type identifier the clients can use to describe the message data payload or reason for message. Optional. String
correlationId A optional user specific identifier that can be used with server requests (iKnowBase.Instant.Atmosphere.request*). The identifier will be present in the corresponding response. String
data The data sent by the publisher. String

Examples

This example establishes a connection to an instant topic, with a single onMessage-callback.

var channel = iKnowBase.Instant.Atmosphere.subscribe ({
    topicName: "/blog/entries",
    atmosphereOptions: {
        onMessage: function (data) { /* Do something with message */ }
    }
});

This example establishes a connection to an instant topic with specified options, including:

Option type Option Value
Topic messageFormat IKB
Topic userList true
Subscription requestUserList true
Subscription subscribeUserListChanges true
Atmosphere transport websocket
Atmosphere onMessage a callback function
Atmosphere onError a callback function
[#ftl]
[#if context.user.isLoggedOn]
	[#assign secureTokenAuth =  "'_ikbUserToken':" + "'" + context.user.token.value + "'"]
[#else]
	[#assign secureTokenAuth = '']
[/#if]
var channel = iKnowBase.Instant.Atmosphere.subscribe ({
    topicName: "/blog/entries?messageFormat=IKB&userList=true",
    subscriptionOptions: {
        requestUserList: true,
        subscribeUserListChanges: true,
        ${secureTokenAuth} // Authentication header from ikbViewer
    },
    atmosphereOptions: {
        transport: "websocket",
        onMessage: function (data) { /* Do something with message */ },
        onError: function (atmosphereResponse) { /* Do something with message */ }
    }
});

Atmosphere.publish

This method establishes a topic-specific channel between the client and a server. The method also sets up callbacks for various events.

Syntax

iKnowBase.Instant.Atmosphere.publish (channel, data)
Parameter Description Type
channel Channel to publish message on, as returned from subscribe(). Object
data Data to publish on channel. Type depends on topic messageFormat; use hash for IKB and String for TEXT String or Hash

Example

To send a text message on a channel with messageFormat=TEXT

iKnowBase.Instant.Atmosphere.publish (channel, "Everybody, there is cake in the reception!");

To send a direct message on a channel with messageFormat=IKB

iKnowBase.Instant.Atmosphere.publish (channel, {
    toUserName: "NARMSTRONG",
    messageType: "WALK_ON_MOON",
    data: "One giant leap, indeed!"
});

Atmosphere.unsubscribe

This method establishes a topic-specific channel between the client and a server. The method also sets up callbacks for various events.

Syntax

When called without parameters, the unsubscribe-function closes all open connections

iKnowBase.Instant.Atmosphere.unsubscribe ()

When called with a single channel parameters, the unsubscribe-function closes the connection to that channel.

iKnowBase.Instant.Atmosphere.unsubscribe (channel)
Parameter Description Type
channel Channel to unsubscribe to, as returned from subscribe(). Object

Atmosphere.requestUserListUpdate

Request a userList response from the server. Same as subscription option subscribeUserListChanges, but used on demand.

Syntax

iKnowBase.Instant.Atmosphere.requestUserListUpdate (channel, correlationId)
Parameter Description Type
channel Channel for requesting the server information, as returned from subscribe(). Object
correlationId An optional user specific identified that will be present in the server response. String

Result is an onMessage call containing IKBResponseMessage with messageType=IKB.USERLIST.RESPONSE and data=List.

Requirements

Active connection on a userList topic.

Example

To request a userList update:

iKnowBase.Instant.Atmosphere.requestUserListUpdate (channel, "MY_CORRELATION_ID");

onMessage response.responseBody:

{
   "toUserName":"ORCLADMIN",
   "fromUser":{
      "guid":null,
      "id":0,
      "username":"ikb$instant",
      "dn":null,
      "label":"iKnowBase Instant Server"
   },
   "messageType":"IKB.USERLIST.USERS",
   "correlationId":"MY_CORRELATION_ID",
   "data":[
      {
         "guid":"BBEA12EB56126795E040000A180038B7",
         "id":58466,
         "username":"KERMIT",
         "dn":null,
         "label":"kermit frog"
      },
      {
         "guid":"8582B1E8B4AA4BDA9B7E0B6422A1D1F7",
         "id":125,
         "username":"ORCLADMIN",
         "dn":"orcladmin",
         "label":"Administrator orcladmin"
      }
   ]
}

Atmosphere.requestUserList

Request a filtered userList response from the server. Typically used to check a subset of the result from subscribeUserListChanges.

Syntax

iKnowBase.Instant.Atmosphere.requestUserList (channel, correlationId, userNames)
Parameter Description Type
channel Channel for requesting the server information, as returned from subscribe(). Object
correlationId An optional user specific identified that will be present in the server response. String
userNames An optional array or ; delimited String of usernames used as filter. String

Result is an onMessage call containing IKBResponseMessage with messageType=IKB.USERLIST.RESPONSE and data=List.

Requirements

Active connection on a userList topic.

Example

To request a filtered userList:

// Example where a full userList would result in ORCLADMIN and KERMIT. Apply KERMIT as filter.
iKnowBase.Instant.Atmosphere.requestUserList (channel, "MY_CORRELATION_ID", "KERMIT");

onMessage response.responseBody:

{
   "toUserName":"ORCLADMIN",
   "fromUser":{
      "guid":null,
      "id":0,
      "username":"ikb$instant",
      "dn":null,
      "label":"iKnowBase Instant Server"
   },
   "messageType":"IKB.USERLIST.RESPONSE",
   "correlationId":"MY_CORRELATION_ID",
   "data":[
      {
         "guid":"BBEA12EB56126795E040000A180038B7",
         "id":58466,
         "username":"KERMIT",
         "dn":null,
         "label":"kermit frog"
      }
   ]
}

Atmosphere.requestSubscribeUserListChanges

Enable or disable join/leave updates for the active connection. Same as subscription option subscribeUserListChanges, but used on demand.

Syntax

iKnowBase.Instant.Atmosphere.requestSubscribeUserListChanges (channel, correlationId, newSubscribeUserListChangesState)
Parameter Description Type
channel Channel for requesting the server information, as returned from subscribe(). Object
correlationId An optional user specific identified that will be present in the server response. String
newSubscribeUserListChangesState Boolean for if subscribeUserListChanges should be enabled(true) or disabled(false). Boolean

Result is an onMessage call containing IKBResponseMessage with messageType=IKB.USERLIST.RESPONSE and data=List.

Requirements

Active connection on a userList topic.

Example

To enable subscribeUserListChanges:

iKnowBase.Instant.Atmosphere.requestSubscribeUserListChanges (channel, "MY_CORRELATION_ID", true);

onMessage response.responseBody:

{
   "toUserName":"ORCLADMIN",
   "fromUser":{
      "guid":null,
      "id":0,
      "username":"ikb$instant",
      "dn":null,
      "label":"iKnowBase Instant Server"
   },
   "messageType":"IKB.USERLIST.SUBSCRIBE.RESPONSE",
   "correlationId":"MY_CORRELATION_ID",
   "data":"Change request for SubscribeUserListChanges: old=false; new=true"
}

To disable subscribeUserListChanges:

iKnowBase.Instant.Atmosphere.requestSubscribeUserListChanges (channel, "MY_CORRELATION_ID", false);

onMessage response.responseBody:

{
   "toUserName":"ORCLADMIN",
   "fromUser":{
      "guid":null,
      "id":0,
      "username":"ikb$instant",
      "dn":null,
      "label":"iKnowBase Instant Server"
   },
   "messageType":"IKB.USERLIST.SUBSCRIBE.RESPONSE",
   "correlationId":"MY_CORRELATION_ID",
   "data":"Change request for SubscribeUserListChanges: old=true; new=false"
}

setDefaultOptions

This method sets default options to be used for all future subscribe-calls

Syntax

iKnowBase.Instant.setDefaultOptions (options)

When called with a single channel parameters, the unsubscribe-function closes the connection to that channel

iKnowBase.Instant.Atmosphere.unsubscribe (channel)
Parameter Description Type
options Options to be used, a combination of iKnowBase- and Atmosphere specific options. See Atmosphere.subscribe() for details. Hash

Complete example

functon displayMessageNotification (data) {
    iKnowBase.notify({
        title: "New message received",
        text: data
    });
}

var channel = iKnowBase.Instant.Atmosphere.subscribe ({
    topicName: "/blog/entries",
    atmosphereOptions: {
        transport: "websocket",
        onMessage: displayMessageNotification
    }
});