LittleCub Forms

Light-Weight, High-Performance & Easily Customizable

LittleCub supports two styles of API, native and jQuery. If you only use Native API, you won't need to include the jQuery library.

LittleCub is the global namespace of this library. It is the entry API for you to initialize a form control and render it as HTML markups within a DOM element.

LittleCub (data, configs, schema, domElem)

Native API for initializing a new form control based on the input parameters. All four parameters are optional. However you will need to at least provide one of the data, configs and schema parameters.

Instead of using LittleCub, you can also use its short name LC.

Returns

An initialized LittleCub form control.

Parameters

Name Description Type Required
data Initial JSON data that will be bound to the rendered form control. It will also be used to decide the control type if the configs and schema don't provide that information. json No
configs A JSON document that contains all control related settings such as control type, size of text field etc. json No
schema A JSON schema document that describe data structure, format and validation rules. json No
domElem A DOM element that will server as the container element for the form control rendition. If this parameter is provided, LittleCub will render the form control as HTML markups based on the control's theme and template setting. Otherwise, it will only initialize the control and you will need to use the control's render method for form rendition. DOM No

Examples

// Example 1
// Renders a single text control within the DOM element with id text-control-1.
// The text field has initial value Sample.
var textControl1 =  LittleCub("Sample", null, null,document.getElementById('text-control-1'));

// Example 2
// Initializes a text control and bind it with data sample. But no form rendition as this point.
var textControl2 =  LittleCub("Sample");
// Now renders the text control within the DOM element with id text-control-2
textControl2.render(document.getElementById('text-control-2'));
// Uses the same control to render a new text control into
// a different DOM element with different data.
textControl2.render(document.getElementById('text-control-3'), "Sample2");

// Example 3
// Renders an array control with a dynamic list of text controls.
var arrayControl1 =  LittleCub(["Sample1","Sample2"], null, null,
    document.getElementById('array-control-1'));
// Renders the same array data as a drop-down select control because of the settings in configs.
var selectControl1 =  LittleCub(["Sample1","Sample2"], {
    "type" : "select"
    }, null,document.getElementById('select-control-1'));
// Renders an array control with a dynamic list of text controls.
// Each text field has length 25 and a validation error will be displayed
// is the length of text input is less than 4.
var arrayControl2 =  LittleCub(["Sample1","Sample2"], {
        "type" : "array",
        "items" : {
            "type" : "text",
            "size" : 25
        }
    }, {
        "type" : "array",
        "items" : {
            "type" : "string",
            "minLength" : 4
        }
    },document.getElementById('array-control-2'));

$.littlecub(data, configs, schema, domElem)

jQuery API that has same behavior as the Native API. Instead of using $.littlecub, you can also use its short name $.lc.

$(selector).littlecub(data, configs, schema)

jQuery API that initializes form control(s) and renders the form controls into the DOM element(s) returned from the jQuery selector.

Instead of using $(selector).littlecub, you can also use its short name $(slector).lc.

Returns

Single form control if the jQuery selector returns single DOM element. List of form controls if the selector returns multiple DOM elements.

Examples

// Renders single text field within the DOM element with id text-control-1.
var textControl1 =  $('#text-control-1').lc("Sample");
// Renders a text field for each DOM element with class text-control.
var textControls =  $('.text-control').lc("Sample");
// Renders an array control with a dynamic list of text controls.
var arrayControl1 =  $('#array-control-1').lc(["Sample1","Sample2"], {
        "type" : "array",
        "items" : {
            "type" : "text",
            "size" : 25
        }
    }, {
        "type" : "array",
        "items" : {
            "type" : "string",
            "minLength" : 4
        }
    });

Methods


id ( )

Generate a unique LittleCub id such as lc-12.

Returns

A unique LittleCub id.

Examples

LittleCub.id();

typeControlClass (type, ControlClass)

Retrieve control class for provided data type or register a default control class to data type mapping if both type and class parameters are provided.

Returns

The mapped control class.

Parameters

Name Description Type Required
type Data type defined by JSON schema string Yes
controlClass Control class class No

Examples

// Registers the text control class to type string mapping.
LittleCub.typeControlClass("string", LittleCub.TextControl);
// Retrieves the control class mapped to type string.
LittleCub.typeControlClass("string");

formatControlClass (format, ControlClass)

Retrieve control class for provided format or register a control class to format mapping if both format and class parameters are provided.

Returns

The mapped control class.

Parameters

Name Description Type Required
format Data format defined by JSON schema string Yes
controlClass Control class class No

Examples

// Registers the email control class to format email mapping.
LittleCub.formatControlClass("text", LittleCub.EmailControl);
// Retrieves the email control class mapped to type text.
LittleCub.formatControlClass("email");

controlClass (controlType, ControlClass)

Retrieve control class for provided control type or register a control class to control type mapping if both type and class parameters are provided.

Returns

The mapped control class.

Parameters

Name Description Type Required
controlType Control type string Yes
controlClass Control class class No

Examples

// Registers the text control class to type text mapping.
LittleCub.typeControlClass("text", LittleCub.TextControl);
// Retrieves the text control class mapped to type text.
LittleCub.typeControlClass("text");

log (level, msg)

Log a message with the provided logging level. The logging will happen if the provided logging level is same or higher than the global logging level which is defined by LittleCub.logger.level.

Returns

None

Parameters

Name Description Type Required
log Logging level. The mapping for logging level looks like {0: 'debug', 1: 'info', 2: 'warn', 3: 'error'} integer Yes
msg Message to be logged. string Yes

Examples

// Logs a debug message
LittleCub.log(0,"Debugging message");

cloneJSON (json)

Makes a deep copy of the provided source JSON document.

Returns

A deep copy of the source JSON document.

Parameters

Name Description Type Required
json Source JSON document to be cloned json Yes

Examples

var json1 = {"foo" : "bar"};
var json2 = LittleCub.cloneJSON(json1);

registerTheme (theme, themeId)

Register a theme with the given ID.

Returns

None

Parameters

Name Description Type Required
theme Theme definition JSON document. object Yes
themeId Unique theme id that the theme will be registered with. string Yes

Examples

LittleCub.registerTheme({
    "id" : "bootstrap-horizontal",
    "parent" : "bootstrap",
    "title" : "Horizontal Twitter Bootstrap Theme",
    "description" : "Twitter bootstrap theme for rendering basic forms with horizontal styles."
});

findThemeConfig (configId, themeId)

Locate the theme with the given theme ID and then find the theme configuration with the given config ID.

Returns

Theme configuration with the given config ID.

Parameters

Name Description Type Required
configId Theme configuration ID. string Yes
themeId Theme ID of the target theme. If not provided, it will pick the default theme. string No

Examples

LC.findThemeConfig("injection", that.configs["theme"]);

findMessage (messageId, themeId, locale)

Locate the theme with the given theme ID and then find the message associated with the theme with the given message ID and locale.

Returns

None

Parameters

Name Description Type Required
messageId Message ID. string Yes
themeId Theme ID of the target theme. If not provided, it will pick the default theme. string No
Locale Language locale. If not provided, it will pick the default locale. string Yes

Examples

validation["message"] = LC.findMessage("isDatetime", this.configs["theme"]);

findTemplate (themeId, templateId)

Locate the theme with the given theme ID and then find the template associated with the theme with the given template ID.

Returns

A compiled template.

Parameters

Name Description Type Required
themeId Theme ID of the target theme. If not provided, it will pick the default theme. string No
templateId ID of the template to be found. string Yes

Examples

var template = LC.findTemplate(this.configs["theme"], "control_messages");

renderTemplate (themeId, templateId, data)

Locate the theme with the given theme ID, find the template associated with the theme with the given template ID and render the template with the given data.

Returns

String from the rendition.

Parameters

Name Description Type Required
themeId Theme ID of the target theme. If not provided, it will pick the default theme. string No
templateId ID of the template to be found. string Yes
data Source data for template rendition. json Yes

Examples

elem.innerHTML = LC.renderTemplate(child.configs["theme"], "array_item_toolbar", child.configs);

registerTemplate (id, template, isTemplate)

Compile and register the given template with the Handlebars under the give id. It can be either placed in the template namespace or registered as a reusable partial.

Returns

None

Parameters

Name Description Type Required
id Template id that template will be registered under. string Yes
template Template to be registered. string Yes
isTemplate Registered as template if true. boolean No

Examples

LittleCub.registerTemplate(id, templateContent.trim(), true);

loadThemes (themes, callback)

Load set of themes from HTML files and then call the callback once all themes are loaded.

Returns

None

Parameters

Name Description Type Required
themes A list of theme id and theme file path pairs. object Yes
callback Callback function that will be executed once all themes are loaded. function No

Examples

LittleCub.loadThemes({
    "bootstrap" : "../../../themes/bootstrap/bootstrap.html",
    "bootstrap-horizontal" : "../../../themes/bootstrap/bootstrap-horizontal.html"
}, function() {
    ...
});

compare (obj1, obj2)

A deep comparison of two JSON objects.

Returns

True if two objects are identical.

Parameters

Name Description Type Required
obj1 Source JSON object to be compared. json Yes
obj2 Target JSON object to be compared. json Yes

Examples

var isSame = LC.compare([{"foo" : "bar"}], ["foo"]);

isEmpty (obj)

Check if the given object is either NULL or undefined.

Returns

True if the given object is either NULL or undefined.

Parameters

Name Description Type Required
obj JSON object to be checked. json Yes

Examples

// Returns false.
var isEmpty = LC.isEmpty("");

isValEmpty (obj)

Check if the given object has an empty value ( such as "" for string, [] for an array, {} for an object etc.).

Returns

True if the given object has empty value.

Parameters

Name Description Type Required
obj JSON object to be checked. json Yes

Examples

// Returns true.
var isValEmpty = LC.isValEmpty([]);

Members

List of members that are available from BaseControl.


Name Description Type
data Data bound to the control. json
schema Schema bound to the control. json
configs Control configuration. json
container The outer DOM element that the control's highest ancestor is rendered into. DOM
id Unique LittleCub ID for the control. string
path The path for the root control is /. And the path for its descendant will be calculated based on its parent's path and its property key or item index if it is part of an array. For example, for the following json data
{
    "foo" : "bar",
    "foo1" : {
        "foo11" : ["bar11", "bar12"]
    }
}
The path for the control mapped to foo11 will be /foo1/foo11 and the path for bar12 will be /foo1/foo11[1].
string
parent The parent control of the current control. It will be null if this control is the root one. control
children List of child controls of the current control.
field HTML field that rendered for this control. DOM
outerEl The outer most DOM element of the control rendition. DOM
messagesContainer The container DOM for validation messages. DOM

Methods

List of members that are provided by BaseControl.


init

Initialize control data, schema and configs. This method will be invoked when you call LittleCub API to create the control. So this API should only be used when you try to extend it in your custom control.

Returns

None

Parameters

Name Description Type Required

Examples

var control = new controlClass(data, configs, schema);
control.init();

bindData (data)

Bind data with the control. This method will be invoked when you call LittleCub API to create the control. So this API should only be used when you try to extend it in your custom control.

Returns

None

Parameters

Name Description Type Required
data Data to be bound to the control. json Yes

Examples


                

validate

Validation the control according to its schema.

Returns

The control itself.

Parameters

Name Description Type Required
validateChildren Validate children controls. boolean No

Examples

var control = control.validate();
var control2 = control2.validate(true);

isValid (skipValidation)

Check if a control is valid or not. Validation will triggered if skipValidation is not set as true.

Returns

True if the control is valid.

Parameters

Name Description Type Required
skipValidation Skip the actual validation. boolean No

Examples

var isValid = control.isValid();

validationEvent

Returns the event that will trigger the validation.

Returns

Validation event.

Parameters

Name Description Type Required

Examples

 var validationEvent = control.validationEvent();

bindEventListeners

Bind event listeners and also fire lc-update event when the control field is updated.

Returns

None

Parameters

Name Description Type Required

Examples


                

controlByPath (path)

Find control based on its path.

Returns

Control with the given path.

Parameters

Name Description Type Required
path Path to the control. string Yes

Examples

var childControl = control.controlByPath("/foo/bar");

bindDOM

Bind DOM elements to the control such as HTML field, outer element etc.

Returns

None

Parameters

Name Description Type Required

Examples

control.bindDOM();

render (container, data, mode)

Render the control into the provided container with the given data.

Returns

None

Parameters

Name Description Type Required
container The DOM element that the control will be rendered into. DOM Yes
data Data to be rendered with. If not provided, it will user the data bound to the control. json No
mode
  • fill(default): Render the control within the container.
  • insertAfter: Render the control after the container.
string No

Examples

objectControl.render(document.getElementById('content2'), data);
objectControl.render(document.getElementById('content3'), data, 'insertAfter');

val (obj)

Return control value or set control value if obj parameter is provided.

Returns

Control value

Parameters

Name Description Type Required
obj Value to be set. json No

Examples

var val = control.val();
control.val({"foo" : "bar"});

Returns

None

Parameters

Name Description Type Required

Examples


                

LittleClub provides a set of custom helpers for its theme templates.

key_value

Iterate over an object, setting 'key' and 'value' for each property in the object.

Usage

{{#key_value obj}}
    Key: {{key}} // Value: {{value}}
{{/key_value}}

Examples

{{#key_value table}}
<tr>
    {{#key_value value}}
        <td data-licid="{{../key}}-{{key}}">
            {{#each value}}
                {{#object_with_key ../../../controls key=this}}
                    <div>{{include 'control'}}</div>
                {{/object_with_key}}
            {{/each}}
        </td>
    {{/key_value}}
</tr>
{{/key_value}}

each_with_key

Iterate over an object containing other objects. Each inner object will be used in turn, with an added key ("myKey") set to the value of the inner object's key in the container.

Usage

{{#each_with_key container key="myKey"}}
    ...
{{/each_with_key}}

Examples

{{#key_value table}}
<tr>
{{#each_with_key container key="myKey"}}
    {{myKey}}
{{/each_with_key}}

key_value

Iterate over an object, setting 'key' and 'value' for each property in the object.

Usage

{{#key_value obj}}
    Key: {{key}} // Value: {{value}}
{{/key_value}}

Examples

{{#key_value table}}
<tr>
    {{#key_value value}}
        <td data-licid="{{../key}}-{{key}}">
            {{#each value}}
                {{#object_with_key ../../../controls key=this}}
                    <div>{{include 'control'}}</div>
                {{/object_with_key}}
            {{/each}}
        </td>
    {{/key_value}}
</tr>
{{/key_value}}

object_with_key

Iterate over an object, setting the context for the inner template code with the "key" parameter.

Usage

{{#object_with_key obj key=context}}
    ...
{{/object_with_key}}

Examples

{{#object_with_key ../../../controls key=this}}
    <div>{{include 'control'}}</div>
{{/object_with_key}}

include

Render the template specified by the templateId with the context data.

Usage

{{include templateId}}

Examples

{{#each controls}}
    {{include 'array_item_toolbar'}}
    {{include 'control'}}
{{/each}}

injectControl

Render the context which is a control.

Usage

{{injectControl}}

Examples

{{injectControl}}

isContainer

Conditional helper for checking if the control is container or not.

Usage

{{#isContainer type}}
    ...
{{else}}
    ...
{{/isContainer}}

Examples

{{#isContainer type}}
    {{injectControl}}
{{else}}
    <span data-lcid="{{id}}" data-lctype="{{type}}" class="control-group form-horizontal">
        {{include 'control_label'}}
        <div class="controls">
        {{injectControl}}
        </div>
        {{include 'control_helper'}}
        <span data-lcid="{{id}}-messages"></span>
    </span>
{{/isContainer}}

isType

Conditional helper for checking if the control belongs to given types. If multiple types are provided, their type names need to be separated by space.

Usage

{{#isType type(s)}}
    ...
{{else}}
    ...
{{/isType}}

Examples

{{#isType 'radio checkbox'}}
    {{injectControl}}
{{else}}
    {{include 'control_label'}}
    {{injectControl}}
    {{include 'control_helper'}}
{{/isType}}