observable

Get and set

html.observable gives you ability to observe any kind of object - from basic types like String Number Boolean Array and Function.

You want to observe a string.

var helloWorld = html.observable('Hello world!');
Get the value of helloWorld variable.
//get value
helloWorld.data; // "Hello world!"
Set the value of helloWorld variable.
//set value
helloWorld.data = 'Hello HtmlJs';
Other type to observe.
var a = html.observable(1),
b = html.observable(2),
computed = html.observable(function() {
    return a.data + b.data;
});
//computed.data => 3

var array = html.observableArray([1,2,3,4,5]);

_computedFn

-property Function

A reference to the funciton of computed value

var firstName = html.observable('')
    .required('Name is required');
firstName.isValid(); // => false
firstName('Henry');
firstName.isValid(); // => true

// set valid state
firstName(''); // from this line, the data is invalid, however we can set it to valid state
firstName.isValid(true); // => true
firstName.isValid(); // => true

_newData

-property Object

Newest data of observable object, use this property for get/set without side effect

var firstName = html.observable('John');
html(document.body).input.attr({ id: 'firstName' }).value(firstName);
firstName._newData = 'Another name';
html('#firstName').context.value; // => John

_oldData

-property Object

This property contains old data of observable object

bindingNodes

-property Array

The property is to maintains the list of input nodes that the observable object bounded to.
This list is useful for validation and error hanlding.

delay

-method - return html.observable

Set delay time to observable to notify change

ParamTypeDetails
handler Function<Array, observer, input> Required. A function takes validationResults, observer and input as parameters.
var isFormValidated = function (validationResults, observer, input) {
    return firstName.isValid() && lastName.isValid()
};

var firstName = html.observable('Henry');
firstName.setValidationHandler(isFormValidated);

var lastName = html.observable('Ford');
lastName.setValidationHandler(isFormValidated);

setValidationResult

-method - no return

Use to set validation result.

ParamTypeDetails
isValid Boolean Pass true value if the data is valid. Otherwise false.
message String Optional. Message to show when data is not valid.
// custom validation rule
html.observable.validation.beginWith = function(char, message) {
    this.validate(function(newValue, oldvalue) {
        if(newValue.charAt(0).toLowerCase() !== char.toLowerCase()) {
            this.setValidationResult(false, message);
        } else {
            this.setValidationResult(true);
        }
    });
    return this;
};
// custom validation rule usage
var name = html.observable('Someone').beginWith('a');

silentSet

-method -no return

Use to set value without notifying UI and dependencies.

ParamTypeDetails
value Object The new value.
var name = html.observable('Someone');
name.silent('Another name');

subscribe

-method

Subscribe a function to be run when the value changed.

ParamTypeDetails
arg Function<object, object> Function to run when the value of observer changed.
It takes two parameters:
  • newValue - {Object} - Newest value of the data.
  • oldValue - {Object} - Last value that set to observer.
//set value
hellowWorld.subscribe(function(value, lastValue) {
    console.log(value, lastValue);
});

validate

-method -no return

Use to create custom validation rules / trigger validation.

ParamTypeDetails
arguments Function<newValue, oldValue> The callback function will have 2 parameters: oldValue and newValue.
See the example in setValidationResult

validators

-method -return html.array<validators>

All validators of the observer.

validationResults

-method -return html.array<validators>

All validationResults of the observer.

Data <Array>

You can only use these methods as following when you need to observe an array.
All the methods in html.observable above are available for html.observable<Array>

add

-method

Add an object to the list, also update the UI/dependencies.

ParamTypeDetails
object Object New object to add.
index Number (Optional - default 0) Index for new item.
var list = html.observable([1,2,3,4,5,6]);
list.add(7);
list.add(0, 0);

filter

-method -no return

Filter a list and display the searching result.

ParamTypeDetails
searchString String Search string.
var list = html.observable(['Anderson', 'Peter', 'Robin']);
list.filter('an'); // ==> ["Anderson"]
list.filter('er'); // ==> ["Anderson", "Peter"]

getFilterResult

-method -return Array filtered list

Return the filter result.

var list = html.observable(['Anderson', 'Peter', 'Robin']);
list.filter('an'); list.getFilterResult(); // ==> ["Anderson"]
list.filter('er'); list.getFilterResult(); // ==> ["Anderson", "Peter"]

move

-method -no return

Move an item in the list to a new position, also update the UI/dependencies.

ParamTypeDetails
position Number Position of an item.
newPosition Number New position to move to.
var list = html.observable(['Anderson', 'Peter', 'Robin']);
list.move(0, 2);
//list() ==> ['Peter', 'Robin', 'Anderson']

orderBy

-method -return html.observable

Order a list by some criteria, also update the UI/dependencies. Support multiple level order.

ParamTypeDetails
arguments String A string to represent the name of a field in one element of the array. It could be an observed field
Object Required. The structure
  • field - {String} - A string represents a field name in one item of the array.
  • isAsc - {Boolean} - If set to true, sort by ascending; otherwise descending.
Function<item> Required. A function for getting value of a single object in list to compare. Because comparing by reference is impossible.
Additional property
  • isAsc - {Boolean} - If set to true, sort by ascending; otherwise descending.
Array Required. Array which each item can be object/function/string - one of any types above.
var people = html.observable([
{name: 'EEE', age: 20},
{name: 'ABC', age: 50},
{name: 'BBB', age: 25}
]);
people.orderBy('name'); // ==> [{name: 'ABC', age: 50}, {name: 'BBB', age: 25}, {name: 'EEE', age: 20}]
people.orderBy('age'); // ==> [{name: 'EEE', age: 20}, name: 'BBB', age: 25}, {name: 'ABC', age: 50}]
people.orderBy({field: 'name', isAsc: false}); // ==> [{name: 'EEE', age: 20}, name: 'BBB', age: 25}, {name: 'ABC', age: 50}]
people.orderBy({field: 'age', isAsc: false}); // ==> [{name: 'ABC', age: 50}, {name: 'BBB', age: 25}, {name: 'EEE', age: 20}]
people.orderBy([{field: 'age', isAsc: false}, {field: 'age', isAsc: true}]); // ==> [{name: 'ABC', age: 50}, {name: 'BBB', age: 25}, {name: 'EEE', age: 20}]

var orderFn = function(x) {return x.name; };
orderFn.isAsc = false;
people.orderBy(orderFn); // equal to people.orderBy({field: 'name', isAsc: false});

pop

-method -return html.observable

Remove the last item in the observed list, also update the UI/dependencies.

var people = html.observable([{name: 'Brad Pitt', age: 46}, {name: 'Angelina Jolie', age: 34}]);
people.pop();
// people() ==> [{name: 'Brad Pitt', age: 46}]

push

-method -return html.observable

Add a new item at the last position in the list, also update the UI/dependencies..

ParamTypeDetails
obj Object Should be the same type within the list.
var people = html.observable([{name: 'Brad Pitt', age: 46}]);
people.push({name: 'Angelina Jolie', age: 34});
// people() ==> [{name: 'Brad Pitt', age: 46}, {name: 'Angelina Jolie', age: 34}]

remove

-method -return html.observable

Remove an item in the list, also update the UI/dependencies.

ParamTypeDetails
obj Object The item in the list.
var people = html.observable([{name: 'Brad Pitt', age: 46}, {name: 'Angelina Jolie', age: 34}]);
people.remove(people()[0]);
// people() ==> [{name: 'Angelina Jolie', age: 34}]

removeAt

-method -return html.observable

Remove an item by its index in the list, also update the UI/dependencies.

ParamTypeDetails
index Number The index of item in the list.
var people = html.observable([{name: 'Brad Pitt', age: 46}, {name: 'Angelina Jolie', age: 34}]);
people.removeAt(0);
// people() ==> [{name: 'Angelina Jolie', age: 34}]

setFilterResult

-method -no return.

Set the filter result by yourself (using another algorithm instead of default algorithm), keep the original array inside, just update the UI using the result.

ParamTypeDetails
filterResult Array<Object> Required. An array to display. Items in array must be the same type/structure to item in the observed list.
You can clear the filter result manually and display the original array by passing null param.
var people = html.observable([{name: 'Brad Pitt', age: 46}, {name: 'Jennifer Aniston', age: 43}]);
people.setFilterResult([{name: 'Angelina Jolie', age: 34}]);
// people.getFilterResult() ==> [{name: 'Angelina Jolie', age: 34}]

splice

-method -no return.

Remove items/add new items, also update the UI/dependencies.

ParamTypeDetails
index Number Required. An integer that specifies at what position to add/remove items.
howmany Number Required. The number of items to be removed. If set to 0, no items will be removed.
items Object Array<Object> Optional. New items to be added, it can be an item or a list.
If you pass an array, the observed list will add each item one by one. It's slightly different from splice of Array prototype.
var people = html.observable([{name: 'Brad Pitt', age: 46}, {name: 'Jennifer Aniston', age: 43}]);
people.splice(1, 1, {name: 'Angelina Jolie', age: 34});
// people() ==> [{name: 'Brad Pitt', age: 46}, {name: 'Angelina Jolie', age: 34}]

people.splice(1, 0, [{name: 'Pax Thien', age: 12}, {name: 'Zahara Marley', age: 12}]);
// people() ==> [{name: 'Brad Pitt', age: 46}, {name: 'Angelina Jolie', age: 34}, {name: 'Pax Thien', age: 12}, {name: 'Zahara Marley', age: 12}]

swap

-method -no return.

Swap two items in the list, using their indexes, also update the UI/dependencies..

ParamTypeDetails
firstIndex Number The first index of the first item need to swap.
var people = html.observable([{name: 'Brad Pitt', age: 46}, {name: 'Angelina Jolie', age: 34}]);
people.swap(0, 1);
// people() ==> [{name: 'Angelina Jolie', age: 34}, {name: 'Brad Pitt', age: 46}]

where

-method -return html.observable

Filter the observed list using expression, also update UI/dependencies using the result.

ParamTypeDetails
callback Function<Object> Required. The callback using to filter, the callback takes each object in the observed list as parameter.
var people = html.observable([{name: 'Brad Pitt', age: 46}, {name: 'Jennifer Aniston', age: 43}]);
people.where(function(person) {return person.name == 'Jennifer Aniston';});
// people.getFilterResult() ==> [{name: 'Jennifer Aniston', age: 43}]

Validation

You can use these built-in validation rules with fluent API.

equal

Compare to an another object, note that you can't compare to a reference type like object, array

ParamTypeDetails
compareTo String Number Date... Required. The object to compare.
message String Required. The message to show when user types invalid data.
var a = html.observable(123).equal(123, 'Not equal to 123');

isNumber

Check the data is kind of number or string representing a number. Accept float and integer.

ParamTypeDetails
message String Required. The message to show when user types something that's not a number/string of number.
var a = html.observable(123).isNumber('You must enter a number.');

greaterThan

Check the data is greater than a criteria.

ParamTypeDetails
valueToCompare String Number Date

Required. The value to compare to the original data.

message String

Required. The message to show when data is not valid.

var a = html.observable(123)
    .isNumber('You must enter a number.')
    .greaterThan(100, 'You must enter a number greater than 100.');

greaterThanOrEqual

Check the data is greater than or equal a criteria. Similar to greaterThan.

ParamTypeDetails
valueToCompare String Number Date

Required. The value to compare to the original data.

message String

Required. The message to show when data is not valid.

var a = html.observable(123)
    .isNumber('You must enter a number.')
    .greaterThanOrEqual(100, 'You must enter a number greater than or equal 100.');

lessThan

Check the data is less than a criteria.

ParamTypeDetails
valueToCompare String Number Date

Required. The value to compare to the original data.

message String

Required. The message to show when data is not valid.

var a = html.observable(123)
    .lessThan(100, 'You must enter a number less than 100.');

lessThanOrEqual

Check the data is less than or equal a criteria. Similar to lessThan.

ParamTypeDetails
valueToCompare String Number Date

Required. The value to compare to the original data.

message String

Required. The message to show when data is not valid.

var a = html.observable(123)
    .lessThanOrEqual(100, 'You must enter a number less than 100.');

maxLength

Check the max length of a string.

ParamTypeDetails
length Number

Required. The maximum length allowed.

message String

Required. The message to show when data is not valid.

var password = html.observable('123456')
    .maxLength(32, 'Max length of password is 32. Please shorten your password.');

minLength

Check the minimum length of a string.

ParamTypeDetails
length Number

Required. The maximum length allowed.

message String

Required. The message to show when data is not valid.

var username = html.observable('my')
    .maxLength(32, 'Min length of username is 6.');

pattern

Check the string using regular expression.

ParamTypeDetails
reg Regular

Required. The regular expression used to validate data.

message String

Required. The message to show when data is not valid.

var username = html.observable('my')
    .maxLength(32, 'Min length of username is 6.');

range

Validate data within a range.

ParamTypeDetails
min Number Date

Required. Minimum value.

max Number Date

Required. Maximum value.

message String

Required. Message to show when user type some value out of the range.

var username = html.observable(100)
    .range(50, 200, 'Min value is 50 and max value is 200.');

required

Requiring data is not empty.

ParamTypeDetails
message String

Required. Message to show when not fill the input.

var username = html.observable('')
    .required('This field must not be blank.');

stringLength

Validate the length of a string.

ParamTypeDetails
min Number

Required. Message to show when not fill the input.

max Number

Required. Message to show when not fill the input.

min String

Required. Message to show when not fill the input.

var username = html.observable(100)
    .stringLength(6, 32, 'Username must have at least 6 and at most 32 characters.');

Extend html.observable

Validation

You add more validation rules in html.observable through html.observable.validation namespace.
The function to validate data has as many parameters as you want, however you must call validate and setValidationResult methods in html.observable once and only once.

See the example in setValidationResult
Another example.
html.observable.validation.genderAndAge = function(gender, age, message) {
    this.validate(function(newValue, oldValue) {  
        if (newValue.gender != gender || newValue.age < age) {
            this.setValidationResult(false, message);
        } else {
            this.setValidationResult(true);
        }
    });  
    return this;
};
Usage
var person = html.observable({name: 'Nhan Nguyen', gender: 'male', age: 25})
    .genderAndAge('male', 20, 'Require male and greater than 25 years old.');

extensions

You can extend the html.observable via extend namespace html.observable.extensions

Not available now.

Built-in controls

Built-in controls help you to generate DOM elements dynamically with the highest speed ever. You can use this framework just to generate DOM element. Although it's originally built for data-binding. You can easily create your own custom control by extending html.
See the example here for understanding how to create custom control.

The context of HtmlJs is a DOM element. Every control will interact with that element. To change the context, we have 2 ways.

1. Use query. Just a little bit difference is that you don't need to use query method. The html itself is a function used to query and set the context for HtmlJs. The first element found will be the context.
2. Use $ function. Change the context to its parent.

html('#test'); // set the context with an element has id "test"
html('.test'); // set the context with the first element has class "test"

a

-method -return html

Create a tag and append to current DOM element of HtmlJs. This method has 2 overrides.

Create A tag without observe anything.
ParamTypeDetails
text String

Required. Display text for A tag.

href String

Required. Attribute href for the tag.

html(document.body).a('Author', 'mailto:nhan.aswigs@gmail.com');
// the code means creating A tag and append to document.body (current DOM element)
// ==> <a href="mailto:nhan.aswigs@gmail.com">Author<a>
Create A tag and observe text as well as href.
ParamTypeDetails
observer html.observable

Required. Observed data contains text and href.

var authorEmail = html.observable({text: 'Author', email: 'mailto:nhan.aswigs@gmail.com'});

html(document.body).a('Author', 'mailto:nhan.aswigs@gmail.com');
// the code means creating A tag and append to document.body (current DOM element)
// ==> <a href="mailto:nhan.aswigs@gmail.com">Author<a>

authorEmail({text: 'Author', email: 'mailto:nhanfu@gihub.com'});
// ==> <a href="mailto:nhanfu@gihub.com">Author<a>

append

-method -return html

Append a DOM element to the current context. It uses a callback to render the DOM.
Using this method, you'are able to add some additional View-Logic.

ParamTypeDetails
callback Function

Required. Use to render DOM elements. No parameters passed to the callback.

var author = "someone";
html(document.body).append(function() {
    if (author === 'someone') {
        html.a('Author', 'mailto:unknown email :D');
    } else {
        html.a('Author', 'mailto:nhan.aswigs@gmail.com');
    }
});

attr

-method -return html

Set attributes to an element.

ParamTypeDetails
attributes Function

Required.
A plain object contains attribute keys and values. This method can observe each property in the object if it is kind of html.observable

Object

Required.
An observed data contains attribute keys and values. UI will be updated automatically when the observed data changed.

Usage
html(document.body).a('Author', 'mailto:author@gmail.com').attr({style : 'background-color: blue;'});
// or usage like this
var attr = html.observable({style : 'background-color: blue;'});
html(document.body).a('Author', 'mailto:author@gmail.com').attr(attr);

button

-method -return html

Create button and append to the current context of HtmlJs.

ParamTypeDetails
text String

Required. Text for the button.

Usage
html(document.body).button('Add new record');
// ==> <button>Add new record</button>

br

-method -return html

Create BR tag and append to the current context of HtmlJs.

html(document.body)
    .button('Add new record')
    .br()
    .button('Delete selected record');
/* HTML code generated */
/* <body>
        :previous code
       <button>Add new record</button>
       <br />
       <button>Delete selected record</button>
   </body>
*/

checkbox

-method -return html

Create input tag with type is "checkbox" and append to the current context of HtmlJs.
If the current context is already input tag then HtmlJs won't generate again, only set its checked property

ParamTypeDetails
checked Boolean

Required. Checked value for the checkbox.

html.observable

Required. Observed data contains checked value for the checkbox.

html(document.body).checkbox(true); // ==> checked
var checked = html.observable(false);
html(document.body).checkbox(checked); // ==> not checked

clss - className

-method -return html

Those methods are interchangeable, used to set and observe class name for a DOM element.

ParamTypeDetails
className String

Required. className for the element.

html.observable

Required. Observed data contains className for the element.

html(document.body).checkbox(true); // ==> checked
var checked = html.observable(false);
html(document.body).checkbox(checked); // ==> not checked

css

-method -return html

Add style to the DOM element, override if the style has been added.

ParamTypeDetails
css Object

Required. Contains css keys values.
For example: {'background-color': 'dark', color: 'green'}

html.observable

Required. Observed data contains css keys values.

displayErrorMessage

-method - no return

Default error handler. Override this function when you want to display in another way, e.g popover, tooltip,...

ParamTypeDetails
validationResults Array

Required. All validation results.

observer html.observable

Required. The observer that bound to the HTML control.

element HTML Element

Required. Element that trigger validation.

var cities = html.observable([{name: "Sai Gon", key: 'sg'}, {name: "Ha Noi", key: 'hn'}]);

html(document.body).dropdown(cities, cities()[0], 'name', 'key');

div

-method -return html

Render DIV tag. No parameters required.

dropdown

-method -return html

Render select tag and its options.

ParamTypeDetails
list Array html.observable<Array>

Required. List of options.

current Object html.observable

Required. Current value for the select tag.

displayField String

Optional. Use to get and set the text to display in each option tag.

valueField String

Optional. Use to get and set the value in each option tag.

var cities = html.observable([{name: "Sai Gon", key: 'sg'}, {name: "Ha Noi", key: 'hn'}]);

html(document.body).dropdown(cities, cities()[0], 'name', 'key');

each

-method -return html

Takes a list and callback as parameter, using the callback to render the UI.
The UI will be update automatically whenever the data in the list changed via html.observable<Array> APIs like add, remove, removeAt, push, pop
See the html.observable<Array> APIs.

NOTE: You can render anything you want in the callback, from the simplest to the most complicated structure. However you need to care about the context of the framework. The framework always keeps a DOM element reference as context. When you use any other DOM-builder methods, the framework will generate DOM element and append to the context. That's why you'll usually use $ method to go

ParamTypeDetails
list Array html.observable<Array>

Required. The list to render. The list can be observed Array.

renderer Function<item, index>

Required. The function to render the UI, this is called renderer.
Renderer takes two parameters:

1. item
2. index

See the example in tutorial Simple list and Complex list and More complex list
Code snippet
html('#SList ul').each(smartPhoneList, function(phone, index){
    html.li(phone);
});
NOTE that inside the callback, the context is automatically set to element before .each method, in this case is '#SList ul'.

empty

-method -return html

Clear all child elements in the current element of HtmlJs. No parameters required.
This method will also remove all the events binding to its child elements via HtmlJs.
In the future, this method can remove all event binding via jQuery and others framework.

html(document.body).empty();

h1..6

-method -return html

Create h1, h2, h3, h4, h5, h6 element. If you want to observed its text, please use text binding control.

html(document.body).h1('h1 element');
html(document.body).h2('h2 element');
html(document.body).h3('h3 element');
html(document.body).h4('h4 element');
html(document.body).h5('h5 element');
html(document.body).h6('h6 element');

i

-method -return html

Create I tag element. If you want to observed its text, please use text binding control.

html(document.body).i().className('fa fa-book');

id

-method -return html

Set the id of current element of HtmlJs.
Quick access to any DOM element by its id. This feature is to avoid hard code when query element.

html(document.body).i().className('fa fa-book').id('bookIcon');
// ==> <i class="fa fa-book" id="bookIcon"></i>
html(html.id.myId).context === html('#myId").context // ==> true

iff

-method -return html

Render data with condition. If the condition is truth, then run renderer otherwise remove all controls that htmljs has built.

ParamTypeDetails
observer Boolean html.observable<Boolean> Required.
renderer Function

Required. The renderer to run when the condition is true.

html(document.body).i().className('fa fa-book').id('bookIcon');
// ==> <i class="fa fa-book" id="bookIcon"></i>

input

-method -return html

Create input with type is text. If its value is an observer, then the observer will notify change immediately by default. This kind of default is set via a global configuration html.config.lazyInput. If set to true, all observer will notify change immediately by default. If set to false, then the observer only notifies change when change event triggered.

ParamTypeDetails
observer Object html.observable<Object>

Required. Can be plain object or html.observable
If it is observed data, then set observer.lazyInput to change the behaviour of the input.

observer.lazyInput = true : observer won't notify change until change event.
observer.lazyInput = false : observer will notify immediately after any key down event.

validationHanlder Function<invalidEvent>

Optional. The function to handle validation event, the event is trigger by the time observer notifies change.
By default, a message appears after the input.

var name = html.observable("Jonny").required('Name is required.');
name.lazyInput = true;
html(document.body).value(name, function(e) {
    // only log invalid event
    console.log(e);
});

li

-method -return html

Create LI (list item) element.

ParamTypeDetails
text String html.observable<String>

Required. Text of the element, can be plain object or html.observable

See the example in Simple list
html('#SList ul').each(smartPhoneList, function(phone, index){
    html.li(phone);
});

option

-method -return html

Create OPTION element. You'll usually use dropdown control to render a dropdown.
This built-in control is for lower level manipulation.

ParamTypeDetails
text String html.observable<String>

Required. Text of the element, can be plain object or html.observable

value String html.observable<String>

Required. Value of the OPTION element, can be plain object or html.observable

isSelected Boolean html.observable<Boolean>

Required. Selected attribute for the OPTION tag.

quickEach

-method -return html

Quick render for a list. Similar usage to .each()
However, this method won't subscribe anything. Use this when you want to save memory.

radio

-method -return html

Render radio button.

ParamTypeDetails
name String

Required. The name attribute of the radio.

value String

Required. Value of the radio.

checked Boolean html.observable<Boolean>

Optional. If true then the radio will be checked, otherwise not checked.

-method -return html

Render a searching input, used to quick filter an array in a list.
Filter result will be display instead of original list.
Clear searchbox to get the original list. See setFilterResult for more info.

ParamTypeDetails
observedArray html.observable<Array>

Required. The observed array to search.

initData html.observable<String>

Optional. Initial value of searchbox. If this is null, then the initial value would be an empty string.

See the example in filter
html('#test-filter #searchStr').searchbox(vm.seats);

select

-method -return html

Render SELECT tag. No parameters required.
You'll usually use dropdown instead of this method.

space

-method -return html

Render spaces.
You don't need to use end method when using this method. See end method for more details.

ParamTypeDetails
numOfSpaces Number

Required. How many spaces you want to render.

html(document.body).spaces(4);

span

-method -return html

Render SPAN element. The text in the span element can be observed.

ParamTypeDetails
text String

Required. The text to display in span tag.

html.observable<String>

Required. Observed text to display in span tag.

html(document.body).spaces(4);

table

-method -return html

Render TABLE element. No parameters required.

html(document.body).table();

tbody

-method -return html

Render TBODY element. No parameters required.

html(document.body).table().tbody();

td

-method -return html

Render TD element.

ParamTypeDetails
text String

Optional. The text to display in TD tag.

html.observable<String>

Optional. Observed text to display in TD tag.

html(document.body).table().tbody().tr()
    .td('First data row').$()
    .td('Second data row').$();

/* Generated HTML code as following */
/*<table>
    <tbody><tr>
        <td>First data row</td>
        <td>Second data row</td>
    </tr></tbody>
</table>*/

text

-method -return html

Render text for an element. This method is usually used to create observed text.

ParamTypeDetails
observer String

Required. The text to display.

html.observable<String>

Required. Observed text to display.

var author = html.observable('Shakespeare');
html(document.body).span().text(author);

th

-method -return html

Render TH element.

ParamTypeDetails
observer String

Optional. The text to display.

html.observable<String>

Optional. Observed text to display.

html(document.body).table().thead()  
    .th('First table header').$()
    .th('Second table header').$();
    
/*<table>
    <thead><th>First table header</th><th>Second table header</th></thead>
</table>*/

thead

-method -return html

Render THEAD element. No parameters required.

See the example of th method.

tr

-method -return html

Render THEAD element. No parameters required.

See the example of td method.

ul

-method -return html

Render UL element. No parameters required.

See the Tutorial of Simple list for more details.
html(document.body).ul().each(smartPhoneList, function(phone, index) {
    html.li(phone);
});

$ - end

-method -return html

This is the most special method in HtmlJs. This method doesn't create any element but set the context HtmlJs to its ancestor.
You can imagine this method like ending tag in HTML. So that some methods in HtmlJs doesn't require $ method when you need to render/data-binding with hierarchical structure. This method gives you ability to use fluent API to render HTML.
Built-in controls don't need $ br, space

ParamTypeDetails
parentSelector String Element

Optional. If you don't pass this parameter, HtmlJs will set the context to its parent.
If it is an Element, the context will be set to that element.
If it is a String, HtmlJs will find the closest element that matches the selector.
You can select many levels to go up. E.g "span p div". In this case, HtmlJs will find SPAN tag first, after that P tag and finally DIV tag.
NOTE: only accept tag selector.

See the Tutorial of Complex list for more details.
html(document.body).div().id('#container') // render a DIV tag with id "container"
    .h1('h1 element').$('div')  // render h1, append to div#container, set the context to parent of h1 - #container
    .h2('h2 element').$()  // render h2, append to #container, also set the context to parent of h2 - #container
Alternative code.
html(document.body).div().id('#container');
html('#container').h1('h1 element');
html('#container').h2('h2 element');

$$ - element

-method - return a DOM element - the context of HtmlJs

$$ and element are actually the same methods.
The current element of HtmlJs. You can use this method to get the context, so that you can render more sophisticated HTML structure that the framework can't support you to do.
However, with some complex HTML structure containing View-Logic you can use append method. It gives you ability to keep using fluent API.

See the Tutorial of Simple list for more details.
html('#container')
    .h1('h1 element').$()  // render h1, append to #container, set the context to parent of h1 - #container
    .h2('h2 element').$()  // render h2, append to #container, set the context to parent of h2 - #container
Alternative code.
html('#container').h1('h1 element');
html('#container').h2('h2 element');

Events

Binding

HtmlJs gives you all possible events in HTML DOM events, you can bind events with ease. The framework will handle for you cross browser binding issues. However because some events are new in HTML5, so be careful when working with them, they can't run in some older browsers.

HtmlJs also gives you ability to bind event with model, just simply passing your model after the event callback as second parameter. And you'll get it at second parameter in callback. This way is extremely useful when binding to you bind events within each callback.

List of all available events.
Mouse events
click, contextmenu, dblclick, mousedown, mouseenter, mouseleave, mousemove, mouseover, mouseout, mouseup
Key events
keydown, keypress, keyup
Frame/object events
abort, beforeunload, error, hashchange, load, resize, scroll, unload
Form events
blur, change, focus, focusin, focusout, inputting, invalid, reset, search, select, submit
Drag events
drag, dragend, dragenter, dragleave, dragover, dragstart, drop
Clipboard events
copy, cut, paste
Print events
afterprint, beforeprint
Media events events
canplay, canplaythrough, durationchange, emptied, ended, error, loadeddata, loadedmetadata, loadstart, pause, play, playing, progress, ratechange, seeked, seeking, stalled, suspend, timeupdate, volumechange, waiting
Animation events
animationend, animationiteration, animationstart
Transition events
transitionend
Misc events
message, online, offline, popstate, show, storage, toggle, wheel
Others events
copy, cut, paste

NOTE: we must use inputting instead of input event, because of conflict with input control.

var clickCallback = function(e, model) {
    console.log(model);
};
html(document.body).button('Test click event with model').click(clickCallback, {username: 'sa', password: '123456'});

trigger

-method - no return

Manually trigger all bound events of an element.

var clickCallback = function(e, model) {
    console.log(model);
};
html(document.body).button('Test click event with model').id('testTrigger').click(clickCallback, {username: 'sa', password: '123456'});
html('#testTrigger').trigger('click');

Promise

-method - return a Promise
ParamTypeDetails
task Function<resolve, reject>

Required. Task to run asynchronously.
See resolve/reject for more details.

resolve/reject

These methods are passed as parameters in html.Promise callback. You must call one of them once and only once when you want to use Promise. The Promise will handle resolve/reject and call every single "done/fail" callback one by one for you.

See the example in the done method

done/fail

-method - return Promise

All callbacks passing via this method will be called after "resolve" called. "done" method can be chained, meaning you can call done as many times as you want.

ParamTypeDetails
callback Function<data> Function<reason>

Required. Callback to run after the task call "resolve/reject".

var promise = html.Promise(function(resolve, reject) {  
    // we visualize a task that run on server for long time.  
    // in real world application, the task is usually an ajax call  
    setTimeout(function() {  
        var success = prompt("Should be done or fail this task?", 1, 0);  
        if (success == '1') {  
            resolve("Ok, we got server's response");  
        } else {  
            reject("Fail to get response from server. Bad request (lol).");  
        }  
    }, 2000);  
});  
  
promise  
    .done(function(data) {  
        console.log(data);  
    }).done(function(data) {  
        console.log(data, 'done the second call');  
    }).fail(function(reason) {  
        console.log(reason);  
    }).fail(function(reason) {  
        console.log(reason, 'fail the second call');  
    });

mockDone/mockFail

-method - return Promise

These methods are for unit test, you can mock "data" for "done" callbacks or "reason" for "fail" callbacks without changing your code.

  1. var promise = html.Promise(function(resolve, reject) {  
  2.     // we visualize a task that run on server for long time.  
  3.     // in real world application, the task is usually an ajax call  
  4.     setTimeout(function() {  
  5.         var success = prompt("Should be done or fail this task?", 1, 0);  
  6.         if (success == '1') {  
  7.             resolve("Ok, we got server's response");  
  8.         } else {  
  9.             reject("Fail to get response from server. Bad request (lol).");  
  10.         }  
  11.     }, 2000);  
  12. });  
Usage of mockDone.
  1. promise  
  2.     .mockDone('Done methods must be run')  
  3.     .done(function(data) {  
  4.         console.log(data);  
  5.     }).done(function(data) {  
  6.         console.log(data, 'done the second call');  
  7.     }).fail(function(reason) {  
  8.         console.log(reason);  
  9.     }).fail(function(reason) {  
  10.         console.log(reason, 'fail the second call');  
  11.     });  
Usage of mockFail
  1. promise  
  2.     .mockFail('Fail methods must be run')  
  3.     .done(function(data) {  
  4.         console.log(data);  
  5.     }).done(function(data) {  
  6.         console.log(data, 'done the second call');  
  7.     }).fail(function(reason) {  
  8.         console.log(reason);  
  9.     }).fail(function(reason) {  
  10.         console.log(reason, 'fail the second call');  
  11.     });  

Ajax

-method - return Promise
ParamTypeDetails
url String Required. URL to submit ajax request.
data Object Optional. Parameters submitting to server.
method String Optional - default "GET". Only accept "GET" or "POST".
async Boolean Optional - default true.
If true then ajax request would be asynchronous otherwise synchronous.
var ajax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);

async

-method - return Promise

Set ajax request to be asynchronous or synchronous. This method also override async value if it has been set. Default behaviour of ajax request is asynchronous, you'll usually use this method when you want to change to synchronous.

ParamTypeDetails
isAsync Boolean Required. If true then ajax request would be asynchronous otherwise synchronous.
var myAjax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);
myAjax.async(false); // set the ajax request to be synchronous

authenticate

-method - return Promise

Set the authentication of ajax request. Only use this method when your server requires authentication.

ParamTypeDetails
username String Required. Username.
password String Required. Password.
var myAjax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);
myAjax.authenticate("myname", "myPassword"); // set the authentication info

contentType

-method - return Promise

Set "Content-type" header in the request.

ParamTypeDetails
contentType String Required. Content-type value.
var myAjax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);
myAjax.contentType('application/xml');

header

-method - return Promise

Set the header of ajax request.

ParamTypeDetails
header Object Required. Header of ajax request. You need to create a JSON object with structure for keys as header keys and values as header values.
See the example for more details.
var myAjax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);
myAjax.header({'Content-type': 'application/json', 'cache-control': 'no-cache'});

get

-method - return Promise

Set type of submit method to "GET". Override old value if it has been set.

var myAjax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);
myAjax.get();

jsonp

-method - return Promise

In case you want a cross origin request. You must use this method.

ParamTypeDetails
callback Function<data> Required. Callback to run when jsonp has been responded.
var myAjax = html.ajax('/anotherServerURL/', {pageIndex: "1", : pageSize "10"});
myAjax.jsonp(function(data) {
    console.log(data);
});

parser

-method - return Promise

Parser for response data. Parse the response before sending to "done" callbacks.

ParamTypeDetails
parser Function<data> Required. Function to parse the data.
var myAjax = html.ajax('/anotherServerURL/', {pageIndex: "1", : pageSize "10"});
myAjax.parser(JSON.parse);

post

-method - return Promise

Set type of submit method to "POST". Override old value if it has been set.

var myAjax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);
myAjax.post();

timeout

-method - return Promise

Set timeout for ajax request. After timeout period, all "fail" methods will be triggered, will the reason is "timeout".

ParamTypeDetails
timeout Number Required. Milliseconds.
var myAjax = html.ajax('myAjaxURL', {pageIndex: "1", : pageSize "10"}, 'POST', true);
myAjax.timeout(2000) // 2 seconds
      .fail(function(reason) {
          console.log(reason); // "timeout"
      });

getJSON

-method - return Promise

Get JSON, shorthand for ajax request with JSON parser and "GET" method.

ParamTypeDetails
url String URL for the request.
data Object Parameters for the request.
NOTE: Because this is get request, so the parameters will be append to URL automatically, so be careful if you want too many parameters.
async Boolean If true, then request will be asynchronous otherwise synchronous.
var myAjax = html.getJSON('myAjaxURL', {pageIndex: "1", : pageSize "10"}, true);
myAjax.done(function(data) {
    console.log(data);
});

postJSON

-method - return Promise

POST JSON, shorthand for ajax request with JSON parser and "POST" method.

ParamTypeDetails
url String URL for the request.
data Object Parameters for the request.
async Boolean If true, then request will be asynchronous otherwise synchronous.
var myAjax = html.postJSON('myAjaxURL', {pageIndex: "1", : pageSize "10"}, true);
myAjax.done(function(data) {
    console.log(data);
});

Scripts/Styles loading

You can use HtmlJs to load script and CSS dynamically. Some advanced feature like RequireJs is not supported in this framework.

scripts/styles

-method - no return

Declare script/style bundles. This method is just for declaration. After this, you must call render.

ParamTypeDetails
bundles Object Script/style bundles.
html.scripts({
    jQuery: ['jquery-1.11.1.js', 'jqueryui.js'],
    html: 'html.engine.js'
});

html.styles({  
    'main': 'css/main.css',
    libs: ['css/bootstrap.css', 'css/bootstrap-datepicker.css']
}); 
The bundles can contain an url list or just an url.

done

-method - return scripts

Used to execute a function after finishing loading a script bundles, you can't do that similar to style bundle.
You must use this method after using render or then method.

ParamTypeDetails
callback Function<modules> Callback to execute after a bundle loaded.
It takes as many modules as you want to inject.
modules String Array<String> Modules to inject along with done function, can be stand alone module or a bunch of modules. Those modules will be injected through "done" callback
See the example in render method.

render

-method - return scripts

Render a script/style bundle that has been registered via scripts/styles method. If the bundle has been registered, you only need to pass the name of it. If the bundle hasn't been declared, you must pass the url of scripts/styles. Note that scripts.render is different from styles.render.

ParamTypeDetails
bundle String Bundle's name that has been registered / a single script
Array Array of script/style urls.
html.scripts({
    jQuery: ['jquery-1.11.1.js', 'jqueryui.js'],
    html: 'html.engine.js'
});

html.styles({  
    'main': 'css/main.css',
    libs: ['css/bootstrap.css', 'css/bootstrap-datepicker.css']
});

html.scripts.render('jQuery').done(function ($) {
    //Do something when jQuery has been loaded
    console.log('jQuery has been loaded', $);
}, '$');

then

-method - return scripts

Render more bundles. This method can be chained.

ParamTypeDetails
bundle String Bundle's name that has been registered / a single script
Array Array of script/style urls.
html.scripts({
    jQuery: ['jquery-1.11.1.js', 'jqueryui.js'],
    html: 'html.engine.js'
});

html.styles({  
    'main': 'css/main.css',
    libs: ['css/bootstrap.css', 'css/bootstrap-datepicker.css']
});

html.scripts.render('jQuery').done(function(){  
    //Do something when jQuery bundle has been loaded
    console.log('jQuery has been loaded');
}).then('html').then('angular.js').done(function() {
    //Do something when HtmlJs and AngularJs bundles have been loaded
    console.log('HtmlJs and AngularJs have been loaded.');
});

Module

This feature is similar to RequireJs, the sake is to hide global variables. But this feature doesn't require you to fully support in all Js files. You can bundle Js files at build time and export your object through a key, another module will access your object by that key.

module

-method - return Object or void

Define a module by a key or import a module by its key.

ParamTypeDetails
key String Key of your module.
obj Object Optional. Object for export. If this parameter is not set, it means getting a module that has been registered by a key.
Export jQuery
html.module('$', jQuery);
Import jQuery
var $ = html.module('$');
console.log($); // ==> jQuery function

Routing

You can use built-in routing in HtmlEngineJs. This is very simple and straightforward. Simply register a pattern along with a callback. Whenever the current url matches the pattern, then the callback will be triggered. You'll also get all parameters needed in the url. With a little configuration, you can use history of HTML5 or fallback to hashtag.

ConfigTypeDetails
html.config.historyEnabled Boolean If false, not to push new state nor pop old state. If true, push every new url into history. Pop state when user click on "Back" button of browser. Run the associated functions that bound with url pattern.

// config to enable history, this property by default is true.
html.config.historyEnabled = true;

// Register route
html.router.when('#user/:id/details', function (id) {
    // do something when user click to user's details with id parameter
    console.log(id);
});

ignoreRoute

-method - return html

Ignore a pattern. When the url matches that pattern, not to push to history, not to execute any function registered via HtmlEngine.

ParamTypeDetails
pattern Object Pattern to ignore.
html.ignoreRoute('#:hashtag'); // ignore all hash tags
html.ignoreRoute('/myLink'); // only ignore "/myLink"

done

-method - return Router

One way to set callback when the route is matched using fluent API.

ParamTypeDetails
callback Function Callback to run.
// Register route  
html.router.when('#user/:id/details')
    .done(function (id) {  
        // do something when user click to user's details with id parameter  
        console.log(id);  
    });  

navigate

-method - return html

Go to a specific URL, invoke the function that has been registered along the URL or pattern of URL if any. Push into history if it's enabled.

ParamTypeDetails
url String URL to go.
html.navigate('/myURL');

partial

-method - return Router

Load a partial view when processing a route.

ParamTypeDetails
url String Required. The URL of the view you need to load when processing a route.
containerSelector String Required. A container to append the view.
html.router.when('/user/:id/details')
    .partial('myView.html', '#myContainer')
    .done(function (id) {
        console.log(id);
    });

process

-method - no return

No parameters. Usually, you need to call this method to execute current url (invoke the function registered with current url).

html.router.process();

router

-method - return Router

Register a pattern along with a function. The function will be trigger with associated parameters in URL.

ParamTypeDetails
pattern String Required. Pattern to register.
callback Function Optional. Function to be invoked when URL matches the pattern.
var loadUserDetails = function (id) {
    // do some ajax request here to load user details
    html.ajax('/user/details/' + id)
        .done(function(userData) {
            // render user details here when data has been loaded
            console.log(userData);
        });
};

html.router.when('/user/:id/details', loadUserDetails); // "/user/100/details" for example

scripts

-method - return Router

Register a pattern along with a function. The function will be trigger with associated parameters in URL.

ParamTypeDetails
bundle String Array<String> Required. Bundle to load when the pattern matches URL.
Reference to scripts loading to see how you can register bundle.
html.router.when('/user/:id/details')
    .scripts('myBundle')
    .scripts('myBinding.js')
    .done(function (id) {
        console.log(id);
    });

Array utils

Array utils are extremely easy to use, and extremely useful when working with Array. You can extend Array utils by extending html.array

Usage of Array utils
// declare html-Array-utils
var studentList = html.array([{name: 'Bob', grade: 2}, {name: 'Peter', grade : 5}, {name: 'Angelina', grade: 8}]);  
studentList
    .where(function(s){ return s.grade > 5; })  // find students where their grades are greater than 5
    .select(function(s){ return s.name; });     // only select name from student list

Extending html.array. For example in the framework, I did it as below.
html.array.addRange = function (items) {
    // push all new items into original array
    var res = Array.prototype.concat.call(this, items);
    // return html.array for chaining ability
    return html.array(res);
};

add

-method - return html.array

Add an item into a list. The same to Array.prototype.push

ParamTypeDetails
arguments Object Required. You can pass as many items as you want to.
var arr = html.array([1,2,3,4,5]);
arr.add(6); // add one item into the array
arr.add(7, 8, 9); // add 3 items into the array

addRange

-method - return html.array

Similar to concat in Array.prototype.

ParamTypeDetails
array Array Required. Array to add into original array.
var arr = html.array([1,2,3,4,5]);
arr.add(6); // add one item into the array
arr.add(7, 8, 9); // add 3 items into the array

any

-method - return Boolean

Return true if there's any element in array matching the condition in the expression.

ParamTypeDetails
expression Function<item> Required. Expression that returns a condition. The any function will base on that condition to return value.
var arr = html.array([1,2,3,4,5]);
arr.any( function(item) {return item > 10; } ); // no item greater than 10 ==> false
arr.any( function(item) {return item >= 3; } ); // 3 items less than or equal 3 ==> true

each

-method - no return

Loop through the array; with each step, run the callback with parameter is the item in the loop.

ParamTypeDetails
action Function<item> Required. Action to run each step of looping.
var arr = html.array([1,2,3,4,5]);
arr.any( function(item) {return item > 10; } ); // no item greater than 10 ==> false
arr.any( function(item) {return item >= 3; } ); // 3 items less than or equal 3 ==> true

find

-method - return Object

Loop through the array; find the best item based on comparer.

ParamTypeDetails
comparer Function<item1, item2> Required. A function that takes two item in the list as parameters and return a better one.
mapper Function<item> Optional. Used to map each item in the list into another object. This action will be taken first if exist.
var studentList = html.array([{name: 'Bob', grade: 2}, {name: 'Peter', grade : 5}, {name: 'Angelina', grade: 8}]);  

studentList.find(function(std1, std2) {  
    return std1.grade > std2.grade ? std1: std2;  
});

first

-method - return Object

Loop through the array; find the first item that matches the condition in expression. If the expression is not passed, then the first item of the list will be return. Throw an exception if there's no item found.

ParamTypeDetails
expression Function<item> Required. A function that takes an item in the list as parameter and return a condition.
var studentList = html.array([{name: 'Bob', grade: 2}, {name: 'Peter', grade : 5}, {name: 'Angelina', grade: 8}]);  

studentList.first(function(std) { return std.name.charAt(0) === 'A'; }); // return {name: 'Angelina', grade: 8}
studentList.first(); // return {name: 'Bob', grade: 2}

firstOrDefault

-method - return Object

Loop through the array; find the first item that matches the condition in expression. If the expression is not passed, then the first item of the list will be return. No exception thrown if there's no item found. In that case, return null

ParamTypeDetails
expression Function<item> Required. A function that takes an item in the list as parameter and return a condition.
var studentList = html.array([{name: 'Bob', grade: 2}, {name: 'Peter', grade : 5}, {name: 'Angelina', grade: 8}]);  

studentList.firstOrDefault(function(std) { return std.name === 'Nhan'; }); // return null
studentList.firstOrDefault(); // return {name: 'Bob', grade: 2}

indexOf

-method - return Number

Find index of item in the list. If no item found, then return -1. Support for old browsers that don't have indexOf in Array.prototype

ParamTypeDetails
item Object Required. Item needed to find its index.
var studentList = html.array([1,2,3,4,5]);

studentList.indexOf(4); // return 3

move

-method - no return

Move an item to a new position in the list.

ParamTypeDetails
fromIndex Number Required. Index of the item need to move.
toIndex Number Required. New position of its item (zero based).
var test = html.array([1,2,3,4,5]);

test.move(0, 3); // ==> [2,3,4,1,5]

orderBy

-method - no return

Order the list by some criteria. Support multiple levels. API and usage are similar to orderBy in html.observable - orderBy. Actually they share the same code.

reduce

-method - return Object

Boils down a list of values into a single value. The idea behind is that there is an iterator takes 2 items in the list and make it become one by doing any algorithms, and keep taking another item until there's only one item left.

ParamTypeDetails
iterator Function Required. This function takes 2 arguments.
First, previous reduced value. This value in the beginning is init
Second, the successive item in the list.
init Number
Object
Array
Optional - default []. Init value for reduction.
var test = html.array([1,2,3,4,5]);

// sum all item in an array
test.reduce(function (res, item) {
    return item + res;
}, 0); // ==> 15

reduceRight

-method - return Object

Boils down a list of values into a single value. Similar to reduce but the iterator will take items as arguments from right to the left.

ParamTypeDetails
iterator Function Required. This function takes 2 arguments.
First, previous reduced value. This value in the beginning is init
Second, the successive item in the list.
init Number
Object
Array
Optional - default []. Init value for reduction.
var test = html.array([1,2,3,4,5]);

// sum all item in an array
test.reduce(function (res, item) {
    return item + res;
}, 0); // ==> 15

remove

-method - no return

Remove an item in the list.

ParamTypeDetails
item Function Required. Item to be removed.
var test = html.array([1,2,3,4,5]);

// remove 2 from the list
test.remove(2);
// ==> [1,3,4,5]

removeAt

-method - no return

Remove an item in the list by its index.

ParamTypeDetails
index Number Required. Index of the item in the list.
var test = html.array([1,2,3,4,5]);

// remove item at index 2
test.removeAt(2);
// ==> [1,2,4,5]

replace

-method - no return

Replace an item by another one.

ParamTypeDetails
victim Object Required. Old item need to be replaced.
item Object Required. New item.
var test = html.array([1,2,3,4,5]);

// remove item at index 2
test.removeAt(2);
// ==> [1,2,4,5]

select

-method - return html.array

Select a new array from origin. Based on expression.

ParamTypeDetails
mapper Function<item> Required. Function to map one item into another item.
var test = html.array([1,2,3,4,5]);

// select square
test.select(function(i){ return i*i; }); // ==> [1,4,9,16,25]

// select item plus 1
test.select(function(i){ return i+1; }); // ==> [2,3,4,5,6]

swap

-method - no return

Select a new array from origin. Based on expression.

ParamTypeDetails
index1 Number Required. First index to swap.
index2 Number Required. Second index to swap.
var test = html.array([1,2,3,4,5]);

test.swap(1,3); // ==> [1,4,3,2,5]

where

-method - no return

Filter items in array. Based on expression.

ParamTypeDetails
predicate Function<item> Required. Function to filter items. Only matched items will be return.
var test = html.array([1,2,3,4,5]);

test.where(function(item) { return item > 3; }); // ==> [4, 5]

Other utils

These utils are common used in most project. Especially type checkers.

checker

HtmlEngine has added some checkers (mostly type checkers).
They are isArguments, isArray, isDate, isFunction, isIE, isInDOM, isNotNull, isNoU, isNumber, isRegExp, isString and isStrNumber

Usage
html.isArray([]) // ==> true
html.isArray(123) // ==> false
html.isDate(123) // ==> false
html.isDate(new Date) // ==> true
html.isFunction('test') // ==> false
html.isFunction(function(){}) // ==> true
html.isRegExp("test") // ==> false
html.isRegExp(/test/) // ==> true
html.isNotNull(null) // ==> false
html.isNotNull(123) // ==> true
html.isNotNull(undefined) // ==> false
html.isNotNull(0) // ==> true

html.isNoU(null); // ==> true
html.isNoU(undefined); // ==> true
html.isNoU(1); // ==> false

createElement

-method - return Element

This function will create an element and append to the current context of HtmlJs.

ParamTypeDetails
name String Required. Name of HTML Element you want to create.
var input = html(document.body).createElement('input');
input.value = "Hello";

createEleNoParent

-method - return html

This function will create an element but not append it to anywhere.

ParamTypeDetails
name String Required. Name of HTML Element you want to create.
html.createEleNoParent('input');
input.value = "Hello";

dispose

-method - no return

Remove an element from DOM tree, also remove all events of the element and its children that bound via HtmlJs. In the future this function can remove all events that bound via some popular libraries. This function can't remove closure references of that element. So be carefully when you need to keep a reference in closure.

ParamTypeDetails
element Element Required. Element to dispose.

disposable

-method - no return

Check for an element is still in DOM tree. If it's in the DOM (meaning removed), call dispose to remove all events of its and its children (if it has children). Unsubscribe a subscriber of an observer associated with the element. This function is usually used in a control for avoiding memory leak.

ParamTypeDetails
element Element Required. Element that's possibly disposable.
observer html.observable html.observable<Array> Required. Observer associated with the element.
subscriber Function Required. The function used to update element when observer notifying change.
Here is one of the control in HtmlJs - SPAN
this.span = function (observer) {
    var value = _html.unwrapData(observer);           // get value of observer
    var span = this.createElement('span');         // create span element
    span.innerHTML = value;
    var updateFn = function (val) {                // update function, only run when observer is from html.observable
        span.innerHTML = val;
        html.disposable(span, observer, this);    // dispose span when it isn't in the DOM tree
        if(!html.isInDOM(span)) span = null;            // clear SPAN reference
    }
    this.subscribe(observer, updateFn);            // subscribe update function
    return this;
};

extend

-method - no return

Copy all methods and properties from source object to destination object.

ParamTypeDetails
destination Object Required. Destination object for extending.
source Object Required. Source object for extending.
var src = {FirstName: 'Brad Pitt', Age: 46};
var des = {Job: 'actor', Property: '$1233242234234123123... :v'};
html.extend(src, des);
// des = {FirstName: 'Brad Pitt', Age: 46, Job: 'actor', Property: '$1233242234234123123... :v'};

expando

-method

Get or set an expando property of an element. It's very easy for you to do that in newest browsers but the framework handles for you this method cross browsers.

ParamTypeDetails
key String Required. Key to get or set expando property. If you try to set model with existing key, then the value will be override.
model Object Optional. Value to set. If this parameter is not passed, then the method will be a getter.
html(document.body).expando('myData', 123456);
var test = html(document.body).expando('myData'); // test => 123456

isDirty

-method - return Boolean

Check if an object is dirty.

ParamTypeDetails
obj Object Array Required. The object to check dirty..
var test = html.observable('Someone');
html.isDirty(test); // false

test('Another one');
html.isDirty(test); // true

partial

-method - return Promise

Load a view and append it into an element (aka the context of html).

ParamTypeDetails
url String Required. URL of the view.
var partial = html('div#container').partial('myPartialUrl.html');
partial.done(function () {
	// partial is already appended to div#container
	console.log('Do something here say binding data, events, etc.');
});

query - querySelectorAll

-method return html.observable<Array<Element>>

Query elements use CSS3 in modern browsers, in older browsers, only basic CSS2 allowed. This feature will be improve in the future for cross-browser.

ParamTypeDetails
selector String Required. Key to get or set expando property. If you try to set model with existing key, then the value will be override.
context Object Optional. Current element to from where you want to query.
html.query(document.body);
html.query('div');           // select div tags
html.query('div.someClass'); // select div tag with the className is "someClass"
html.query('div#someId');    // select div tag with the id is "someId"
html.query('div input');     // select input inside div tag
html.query('a[href]');       // select A tag with has "href" attribute

subscribe

-method - no return

Subscribe a function (subscriber) to an observer, whenever the value in observer changed, the change will be notified to the subscriber. This is similar to subscribe in html.observable

ParamTypeDetails
observer html.observable html.observable<Array> Required
subscriber Function Required.

serialize

-method - return Object

Serialize any kind of data structures derived from html.observable or html.observable<Array>. This method is for submitting to server.

ParamTypeDetails
data html.observable html.observable<Array> Required. Data to serialize.

trim

-method - return String

Trim a string left and right.

ParamTypeDetails
str String Required. String to trim.

trimLeft

-method - return String

Trim left a string.

ParamTypeDetails
str String Required.

trimRight

-method - return String

Trim right a string.

ParamTypeDetails
str String Required.

unsubscribe

-method - no return

Unsubscribe a function (subscriber) from an observer. This is similar to unsubscribe in html.observable

ParamTypeDetails
observer html.observable html.observable<Array> Required
subscriber Function Required. The function to unsubscribe.

unbindAll

-method - no return

Unbind all events that bound via HtmlJs of an element.

ParamTypeDetails
element Element Required. Element to unbind.