Origami Frontend Components & Services

Readme: o-comment-utilities

A collection of helper functions used by o-comments and o-chat.

Contents

API

envConfig

This module provides a useful way to handle application level configurations. It supports setting and reading configurations, also overriding existing values (helpful when the application should be working on different environments with partially different configuration).

Constructor

In order to create a configuration, you should create an instance first:

var config1 = new oCommentUtilities.EnvConfig();

In order to keep an isolated configuration object of your application, which is accessible within your whole application, the following method can be used:

var EnvConfig = require('js-env-config');

module.exports = new EnvConfig();

Methods

get

Gets the whole configuration if without parameter, or a field if a field is given as parameter.

Getting the whole configuration object:

config.get();

Getting a field of the configuration object:

config.get('aField');
set

Sets the configuration. The current configuration is merged with this object. Existing fields that have primitive type values and the same field has value in the object given to set, are overwritten.

Setting an object:

config.set({
    'configField': 'value'
});

Setting a key/value:

config.set('aField', {
    'configField': 'value'
});

This is equivalent with the following object:

{
    "aField": {
        "configField": "value"
    }
}

Events

This module helps creating custom events, listening on custom events and triggering them. It is similar to jQuery's event system (except that it doesn't support namespacing).

Constructor

The constructor has no parameter.

var myEvent = new Events();

Methods

on

Registers a new event handler to an event.

myEvent.on(event, handler)

Where:

one

Registers a new event handler to an event. Similar to 'on', but the handler is called only once.

myEvent.one(event, handler)
off

Removes one or more event handlers.

myEvent.off(event, handler)

Where:

If handler is omitted, all event handlers from the event specified are removed.
If both event and handler are omitted, all event handlers are removed.

trigger

Triggers an event: it causes calling all the event handlers that are listening for the event name.

myEvent.trigger(event, customData)

Where:

jsonp

This module provides a similar solution for JSONP communication as jQuery. For more information on JSONP, visit https://www.w3schools.com/js/js_json_jsonp.asp .

The module is actually a single function. It should be called the following way:

commentUtilitis.jsonp({
    url: "URL here",
    data: "Data here" //optional
}, function (err, data) {
    if (err) {
        throw err;
    }

    // use the data
});

Both parameters (configuration object and callback) are required. Also, the configuration should contain the 'url' field.

data

If data should be sent, it can be part of the URL directly, or can be provided as the data field within the configuration object. The data field should be an object with key-value pairs.

callback

The callback has a Node.js inspired form. The first parameter is the error parameter, while the second one is the data parameter received from the server as a response.

scriptLoader

This module provides a similar solution for loading a Javascript file asynchronously as jQuery's $.getScript() (http://api.jquery.com/jquery.getscript/).

The module is actually a single function. It can be called the following ways:

1.

oCommentUtilities.scriptLoader({
    url: "URL here",
    charset: "utf-8" //optional
}, function (err) {
    if (err) {
        throw err;
    }

    // loaded successfully
});

2.

oCommentUtilities.scriptLoader("URL here", function (err) {
    if (err) {
        throw err;
    }

    // loaded successfully
});

Both parameters (configuration object/URL and callback) are required. Also, if the configuration is an object, it should contain the 'url' field.

callback

The callback has a Node.js inspired form. The parameter is either 'null' or an Error instance. If it doesn't contain an error, the loading finished with success.

storageWrapper

Wrapper around localStorage and sessionStorage, but enhanced with automatic type conversion.

Automatic type conversion means the followin: for example, if you store an object which can be serialized into a JSON string, when you read it back you will get the same Javascript object and not just a plain string.

The module exposes two main fields, both having the same API:

oCommentUtilities.storageWrapper.localStorage //wrapper around native localStorage
oCommentUtilities.storageWrapper.sessionStorage //wrapper around native sessionStorage

API of localStorage and sessionStorage

Both submodules has the same public API. The difference is only the place the data is saved (as it is in the native API).

Available methods:

setItem

Saves an item in the storage. It has the following form:

setItem(key, value);

The value is saved in the storage with the key. The value can be looked up using the key provided.

The item is saved in the following format:

{type}|{value converted/serialized to string}

For example, a boolean "true" value is saved in the following way:

boolean|true

Objects that can be serialized are saved with the type "json".

getItem

Reads the item and returns it in the original type that was saved.

getItem(key);

For example, if a boolean true was saved, it is not returned as a string, but as a boolean type.

hasItem

Returns true or false and it says if there is an item with that key.

hasItem(key);
removeItem

Removes the item saved with the key provided.

removeItem(key);
clear

Clears all entries for the current domain.

native

Returns the native localStorage or sessionStorage object.

logger

Logging helper which uses the native "console" to log. It also extends IE8 logging capabilities by stringifying complex objects.

Where console is not available, the logger fails silently.

The module supports the following methods:

Logger configuration

The logger can be configured with the following: enable/disable, set the minimum level that is logged.

By default is logging disabled (recommended settings for production).
Default level of logging is 'warn'.

enable

Enables the logging.

logger.enable();
disable

Disables the logging.

logger.disable();
setLevel

Sets the minimum level that should be logged. The levels are the following:

logger.setLevel(level);

Where level can be:

Logging functions

Available functions:

functionSync

Parallel

This submodule is meant to generate a callback only when all functions provided finished their execution. This is achieved by passing a callback as parameter to the functions that are executed.

The submodule itself is a single function and can be called in the following way:

oCommentUtilities.functionSync.parallel({
    func1: function (callback) {},
    func2: function (callback) {},
    func3: {
        args: ['param1', 'param2'],
        func: function (callback, param1, param2) {}
    }
}, function (dataAggregate) {
    // where data aggregate is:
    // {
    //      func1: 'dataFromFunc1',
    //      func2: 'dataFromFunc2',
    //      func2: 'dataFromFunc2'
    // }
}
});

Functions provided within the object can be in the following forms:

  1. Single function. As example are func1 and func2.
  2. Object with the following fields: func is the actual function that will be called, args are the arguments that are appended after the callback parameter.

For more information on the technical side, please visit the detailed documentation (docs/index.html).

domConstruct

This module is able to instantiate classes extended from o-comment-ui/Widget.js using markup in the DOM.

How to use it

This feature reads the DOM for certain types of elements. An example element:

<div data-o-component="o-chat" id="commentWidget" data-o-chat-config-title="o-chat-test-closed3" data-o-chat-config-url="http://ftalphaville.ft.com/marketslive-test.html" data-o-chat-config-articleId="marketslive-test" data-o-chat-config-order="inverted"></div>

Key parts of the DOM element:

In order to start the DOM construction, the oCommentUtilities.initDomConstruct function should be called with a configuration object, which has the following fields:

Example:

var initDomConstructOnDemand = function () {
    oCommentUtilities.initDomConstruct({
        classNamespace: 'o-chat',
        eventNamespace: 'oChat',
        moduleRef: oChat,
        classRef: oChat.Widget
    });
}

document.addEventListener('o.DOMContentLoaded', function () {
    oCommentUtilities.initDomConstruct({
        classNamespace: 'o-chat',
        eventNamespace: 'oChat',
        moduleRef: oChat,
        classRef: oChat.Widget,
        auto: true
    });
});

In some cases this module should be called on demand by the product, so it could be exposed as a public API as part of the module which uses it.

Example: (from o-chat/main.js)

var Widget = require('./src/javascripts/Widget.js');

exports.init = function (el) {
    return oCommentUtilities.initDomConstruct({
        context: el,
        classNamespace: 'o-chat',
        eventNamespace: 'oChat',
        moduleRef: this,
        classRef: Widget
    });
};

This way all the configurations are abstracted, the product should not care about setting them.

If you want to obtain a reference of the created Class instances, you should listen on the body to the event {namespace}.ready (e.g. oChat.ready), which will have the following details:

Example:

document.body.addEventListener('oChat.ready', function (evt) {
    //evt.detail.id and evt.detail.instance are available
});

The instance that is already created will have a flag that says that it shouldn't be created again, even if initDomConstruct is called again. The flag that is set is data-{namespace}-built="true" (e.g. data-o-chat-built="true"). If you are creating instances in another way (programatically), the container element should have this flag set.

Return value

The return value is an array with all the instances of Class (e.g. oChat.Widget) created.

Helpers for working with cookies.

get

Reads a cookie by name.

oCommentUtilities.cookie.get('name');

set

Sets a cookie.

oCommentUtilities.cookie.set('name', 'value', 36 /*days */);

remove

Removes a cookie

oCommentUtilities.cookie.remove('name');

ftUser

ftUser is a helper for obtaining information about the FT user, information like logged in status, user ID, email address, session ID.

Methods exposed that can be used:

Switch component view

GitHub Repository

Install o-comment-utilities

If using the Build Service, add o-comment-utilities@^2.4.0 to your script tag.

If running a Manual Build, run bower install --save "o-comment-utilities@^2.4.0".

Help & Support

o-comment-utilities is maintained directly by the Origami team. If you have any questions about o-comment-utilities or Origami in general, we are happy to help. 😊

Slack: #ft-origami
Email: origami.support@ft.com

Feedback / Issues

To report a bug or request features please create an issue on Github. For support or general feedback please get in touch 😊

Slack: #ft-origami
Email: origami.support@ft.com