All samples are using Ink.requireModules, please read how to use it at Ink.requireModules section

Ink_1 class

This module provides the necessary methods to create and load the modules using Ink.

Functions
Function name Description
.bind(fn, context) Function.prototype.bind alternative/fallback.
.bindEvent(fn, context) Function.prototype.bind alternative for event handlers.
.bindMethod(object, methodName) Function.prototype.bind alternative for class methods
.createExt(moduleName, version, dependencies, modFn) Creates an Ink.Ext module
.createModule(mod, version, deps, modFn) Creates a new module.
.error() Calls native console.error if available.
.extendObj(destination, source) Extends an object with another
.getModule(mod, [version]) Loads a module.
.getModuleScripts() Builds the markup needed to load the modules.
.getModulesLoadOrder() Lists loaded module names.
.getPath(key, [noLib]) Get the full path of a module.
.i(id) Shorter alias to document.getElementById.
.loadScript(uri, [contentType]) Loads a script URL.
.log() Calls native console.log if available.
.namespace(ns, [returnParentAndKey]) Defines a module namespace.
.requireModules(deps, cbFn) Requires modules asynchronously
.s(selector, [from]) Selects elements like Ink.ss, but only returns the first element found.
.setPath(key, rootURI) Sets the URL path for a namespace.
.ss(selector, [from]) Alias for Ink.Dom.Selector
.warn() Calls native console.warn if available.
Properties
Property name Description
.VERSION

.bind(fn, context) method

Function.prototype.bind alternative/fallback.
Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Accepts

  • fn

    The function
  • context

    The value to be passed as the this parameter to the target function when the bound function is called. If used as false, it preserves the original context and just binds the arguments.
  • more...

    Additional arguments will be sent to the original function as prefix arguments.

How to keep this in the object context

Code

var MyObj = {

    _name: null,

    setName: function(name) 
    {
        this._name = name;
    },

    showNameAfter1Sec: function()
    {
        // success 
        setTimeout(Ink.bind(function() {
            alert(this._name);
        }, this), 1000);
        
        // "this" will be "window", so this._name will be "undefined"
        setTimeout(function() {
            alert(this._name);
        }, 1000);
    }
};

MyObj.setName('John');
MyObj.showNameAfter1Sec(); 

Ink.bind() can be used to pass more arguments to callback function

Code

var MyObj = {

    _name: null, 

    _age: null,

    _setAndAlertInfo: function(name, age) 
    {
        this._name = name;
        this._age = age; 
        alert(this._name +' => '+ this._age);
    },
    
    showInfoAfter1Sec: function(name, age)
    {
        setTimeout(Ink.bind(this._setAndAlertInfo, this, name, age), 1000);
    }
};

MyObj.showInfoAfter1Sec('John', 35);

.bindEvent(fn, context) method

Function.prototype.bind alternative for event handlers.
Same as bind but keeps first argument of the call the original event.
Set context to false to preserve the original context of the function and just bind the arguments.

Accepts

  • fn

    The function
  • context

    The value to be passed as the this parameter to the target
  • more...

    Additional arguments will be sent to the original function as prefix arguments

Ink.bindEvent() is very similar to Ink.bind but it is used to keep the this context in event handlers, and event object is passed to callback as first argument.

Code

<div>
    <button id="my_button_a" class="ink-button">Click me A</button>
    <button id="my_button_b" class="ink-button">Click me B</button>
</div>
<script>
Ink.requireModules(['Ink.Dom.Event_1'], function(InkEvent) {

    var MyObj = {

        _propToAlert: 'Hello World',

        _handlerBinded: null,

        addEvent: function() 
        {
            var elmA = Ink.i('my_button_a');
            var elmB = Ink.i('my_button_b');

            // create a property binded to can be removed later with InkEvent.stopObserving
            this._handlerBinded = Ink.bindEvent(this._doStuffOnClick, this); 
            InkEvent.observe(elmA, 'click', this._handlerBinded);

            // Ink.bindEvent can be used directly in an anonymous function 
            InkEvent.observe(elmB, 'click', Ink.bindEvent(function(event){

                        this._doStuffOnClick(event);
                    
                    }, this));
        },

        _doStuffOnClick: function(event) 
        {
            alert(this._propToAlert + ' => ' + event.type);
        }

    };

    MyObj.addEvent(); 
});
</script>

.bindMethod(object, methodName) method

Function.prototype.bind alternative for class methods
See Ink.bind. The difference between bindMethod and bind is that bindMethod fetches a method from an object. It can be useful, for instance, to bind a function which is a property of an object returned by another function.

Accepts

  • object

    The object that contains the method to bind
  • methodName

    The name of the method that will be bound
  • more...

    Additional arguments will be sent to the new method as prefix arguments.

Build a function which calls method remove of Ink.Dom.Element on an element

Code

<div id="element">
  Text content
</div>
<script>
Ink.requireModules(['Ink.Dom.Element_1'], function(InkElement) {

    var elm = Ink.i('element');
    var methodBinded = Ink.bindMethod(InkElement, 'remove', elm); 
              
    methodBinded();
});
</script>

Comparing with Ink.bind to the same effect. The following two calls are equivalent

Code

Ink.bind(this.doWithSomething, this, 'something');
Ink.bindMethod(this, 'doWithSomething', 'something');

.createExt(moduleName, version, dependencies, modFn) method

Creates an Ink.Ext module

Does exactly the same as createModule but creates the module in the Ink.Ext namespace

Accepts

  • moduleName

    Extension name
  • version

    Extension version
  • dependencies

    Extension dependencies
  • modFn

    Function returning the extension

With Ink.createExt() you can create your own module to Ink. It works like Ink.createModule() but will expose your module in Ink.Ext namespace. With this method you can contribute to Ink project with new modules and we will promote your module in our page. Read how to contribute to Ink in our CONTRIBUTING.md. Ink.createExt() can be used to create your modules to your project.

Here's an example of Ink.Ext.MyAwesomeModule_1

Code

Ink.createExt('MyAwesomeModule', 1, ['Ink.Dom.Event_1'], function(InkEvent) {

    var MyAwesomeModule = function() {
        this._init();
    }; 

    MyAwesomeModule.prototype = {
        _init: function()
        {
            this._doStuff(); 
        },

        _doStuff: function() 
        {
            alert('Doing stuff in MyAwesomeModule');
            /* ... */
        } 
    };

    return MyAwesomeModule; 
});


Ink.requireModules(['Ink.Ext.MyAwesomeModule_1'], function(MyAwesomeModule) {
        
    new MyAwesomeModule(); 
        
});

How to create an UI extension that works with data-attributes as options. This is a simple extension. A clickable div that expands from init height to max heigh.

Code HTML

<!-- Use option with "data-module_name-" prefix to be compatible with other modules -->
<div id="ext-expands" data-expands-init-height="30" data-expands-max-height="150" style="border:1px solid black;">
Click Me
</div>

Code JavaScript

// Create extension Expands

Ink.createExt('Expands', 1, ['Ink.UI.Common_1', 'Ink.Dom.Event_1'], function(UICommon, InkEvent) {

    var Expands = function(selector, options) {
        this._init(selector, options);
    }; 

    Expands.prototype = {
        _init: function(selector)
        {
            this._rootElm = UICommon.elsOrSelector(selector, 'Ink.Ext.Expands root element')[0] || null;

            this._options = UICommon.options({
                    expandsInitHeight: ['Number', 10], // default value to init height
                    expandsMaxHeight: ['Number', 100]  // default value to max height
                }, arguments[1] || {}, this._rootElm);

            this._stout = false;
            this._currentHeight = 0;

            this._addEvent(); 

        },

        _addEvent: function()
        {
            InkEvent.observe(this._rootElm, 'click', Ink.bindEvent(this._onClickElm, this));
        },

        _onClickElm: function(event)
        {
            InkEvent.stopDefault(event);
            if(this._stout) {
                clearTimeout(this._stout);
            }
            this._currentHeight = this._options.expandsInitHeight; 
            this._rootElm.style.height = this._currentHeight+'px';

            this._expands();
        },

        _expands: function()
        {
            if(this._currentHeight >= this._options.expandsMaxHeight) {
                this._stout = false;
                return;
            }
            this._currentHeight += 5;
            this._rootElm.style.height = this._currentHeight+'px';

            this._stout = setTimeout(Ink.bind(this._expands, this), 100);

        }
    };

    return Expands; 
}); 


// Run extension 

Ink.requireModules(['Ink.Ext.Expands_1'], function(Expands){

    new Expands("#ext-expands");

});

.createModule(mod, version, deps, modFn) method

Creates a new module.
Use this to wrap your code and benefit from the module loading used throughout the Ink library

Accepts

  • mod

    Module name, separated by dots. Like Ink.Dom.Selector, Ink.UI.Modal
  • version

    Version number
  • deps

    Array of module names which are dependencies of the module being created. The order in which they are passed here will define the order they will be passed to the callback function.
  • modFn

    The callback function to be executed when all the dependencies are resolved. The dependencies are passed as arguments, in the same order they were declared. The function itself should return the module.

How to create a new Ink's static module ex: Ink.Util.Calculator version 1 without dependencies

This module is static, that means, all methods will be used as Ink.Util.Calculator_1.method();

Code

Ink.createModule('Ink.Util.Calculator', 1,  // define module and version 
        [],  // empty array to define no dependencies 
        function() { // callback function

    var StaticModule = {
        _toNumber: function(str) // private method, should be used only internaly 
        {
            return Number(str);
        },

        add: function(a, b) 
        {
            return this._toNumber(a) + this._toNumber(b);
        },

        subtract: function(a, b)
        {
            return this._toNumber(a) - this._toNumber(b);
        },

        multiply: function(a, b)
        {
            return this._toNumber(a) * this._toNumber(b);
        },

        divide: function(a, b)
        {
            return this._toNumber(a) / this._toNumber(b);
        }
    };

    return StaticModule;
});

// How to use it... see Ink.requireModules to understand how it works 
Ink.requireModules(['Ink.Util.Calculator_1'], function(Calculator) {
    
    Calculator.add(7, '5'); // 12
        
    Calculator.subtract(15, 4); // 11 
        
    Calculator.multiply(7, 6); // 42 
        
    Calculator.divide('a', 'b'); // NaN 
});

How to create a new Ink's instantiable module ex: Ink.UI.ElementClickable version 1 with Ink.Dom.Event_1 and Ink.Dom.Element_1 as dependencies

This module is instantiable, that means, will be used as new Ink.UI.ElementClickable_1();

Code

Ink.createModule('Ink.UI.ElementClickable', 1,  // define module and version 
        ['Ink.Dom.Event_1', 'Ink.Dom.Element_1'],  // array of dependencies 
        function(InkEvent, InkElement) { // callback function with dependencies alias. Using Event/Element as alias can conflit with Event/Element JS global objects

    var ElementClickable = function(options) {
        this._init(options); 
    };

    ElementClickable.prototype = {
        _init: function() // by convention, use _init method as constructor name 
        {
            this._options = Ink.extendObj({
                    label: 'Click me',
                    target: Ink.s('body')
                }, arguments[0] || {});
            
            this._addElementToTarget();
        },

        _createElement: function()
        {
            var div = InkElement.create('div', {setTextContent: this._options.label});
            return this._addEvent(div);
        },

        _addEvent: function(elm)
        {
            InkEvent.observe(elm, 'click', function() {
                    alert('Click');
                });
            return elm; 
        },

        _addElementToTarget: function()
        {
            var elm = this._createElement(); 
            InkElement.insertBottom(elm, this._options.target);
        }
    };
    return ElementClickable;
});
       
Ink.requireModules(['Ink.UI.ElementClickable_1'], function(ElmClickable) {

    new ElmClickable(); 

    new ElmClickable({label: 'Click here please', target: Ink.ss('div')[0]});
});

.error() method

Calls native console.error if available.

Accepts

  • more...

    Arguments to be evaluated

Ink.error() is an alias to console.error() when it is available.

Code

function myFunc(a, b) {
    if(!a || !b) {
        Ink.error('Missing arguments');
    }
    /* ... */
}
myFunc('a');
myFunc(null, 'b');

.extendObj(destination, source) method

Extends an object with another
Copy all of the properties in one or more source objects over to the destination object, and return the destination object. It's in-order, so the last source will override properties of the same name in previous arguments.

Accepts

  • destination

    The object that will receive the new/updated properties
  • source

    The object whose properties will be copied over to the destination object
  • more...

    Additional source objects. The last source will override properties of the same name in the previous defined sources

Copy object person1 to person2

Code

var person1 = {
    name: 'Charles', 
    age: 31,
    married: true
};

var person2 = Ink.extendObj({}, person1); 

/*
   person1 will be: 
   { name: 'Charles', age: 31, married: true }
   person2 will be: 
   { name: 'Charles', age: 31, married: true }
*/

Copy object but define default values in new object.

Code

var person1 = {
    name: 'Charles', 
    age: 31,
    married: true
};

var person2 = Ink.extendObj({
            hasGlasses: true,
            married: false
        }, person1); 
/*
   person1 will be: 
   { name: 'Charles', age: 31, married: true }
   person2 will be: 
   { name: 'Charles', age: 31, married: true, hasGlasses: true }
*/

.getModule(mod, [version]) method

Loads a module.
A synchronous method to get the module from the internal registry.
It assumes the module is defined and loaded already!

Accepts

  • mod

    Module name
  • version

    Version number of the module

.getModuleScripts() method

Builds the markup needed to load the modules.
This method builds the script tags needed to load the currently used modules

.getModulesLoadOrder() method

Lists loaded module names.
The list is ordered by loaded time (oldest module comes first)

.getPath(key, [noLib]) method

Get the full path of a module.
This method looks up the paths given in setPath (and ultimately the default Ink's path).

Accepts

  • key

    Name of the module you want to get the path
  • noLib

    Flag to skip appending 'lib.js' to the returned path.

.i(id) method

Shorter alias to document.getElementById.
Just calls document.getElementById(id), unless id happens to be an element.
If id is an element, Ink.i just returns it.

You can use this in situations where you want to accept an element id, but a raw element is also okay.

Accepts

  • id

    Element ID

Code

<div id="element_id_a">A</div>
<div id="element_id_b">B</div>
<script>

var elmA = Ink.i('element_id_a');  // "div" with id "element_id_a"

var elmB = Ink.i(document.getElementById('element_id_b')); // "div" width id "element_id_b"

var elmC = Ink.i('element_id_c'); // null 

</script>

.loadScript(uri, [contentType]) method

Loads a script URL.
This creates a script tag in the head of the document.
Reports errors by listening to 'error' and 'readystatechange' events.

Accepts

  • uri

    Can be an external URL or a module name
  • contentType

    'text/javascript'The `type` attribute of the new script tag.

.log() method

Calls native console.log if available.

Accepts

  • more...

    Arguments to be evaluated

Ink.log() is an alias to console.log() when it is available.

Code

var varA = {foo: 'bar'};
var varB = 123;
Ink.log(varA, varB);

.namespace(ns, [returnParentAndKey]) method

Defines a module namespace.

Accepts

  • ns

    Namespace to define.
  • returnParentAndKey

    Flag to change the return value to an array containing the namespace parent and the namespace key

.requireModules(deps, cbFn) method

Requires modules asynchronously
Use this to get modules, even if they're not loaded yet

Accepts

  • deps

    Array of module names. The order in which they are passed here will define the order they will be passed to the callback function.
  • cbFn

    The callback function to be executed when all the dependencies are resolved. The dependencies are passed as arguments, in the same order they were declared.

Using Ink.requireModules() in a project is a good practice. All dependencies can be controlled, creating aliases to Inks modules making it more easy to use and all variables will keep in a private project scope instead of global scope.

Here's an example of a MyProject.js file.

Code

Ink.requireModules(     // first line of MyProject.js 
        [               // dependencies array with all needed modules 
            'Ink.Dom.Loaded_1', 
            'Ink.Dom.Event_1', 
            'Ink.Net.Ajax_1'
        ],
        function(Loaded, InkEvent, Ajax) {    // aliases to dependencies modules 

        /* 
         * All project code here 
         */
        var MyProjectConfig = {
            app_name: 'My Awesome Project',
            ajaxEndpoint: '/ajaxendpoint.php'
        };

        function aFunction() {
            InkEvent.observe(document.body, 'click', onClickBody);
        }

        function onClickBody() {
            new Ajax(MyProjectConfig.ajaxEndpoint, {});
        }

        Loaded.run(function() { // run on DOMContentLoaded  
                
                aFunction();        
            
            });


}); // last line of MyProject.js

.s(selector, [from]) method

Selects elements like Ink.ss, but only returns the first element found.

Using sizzle-specific selectors is NOT encouraged!

Accepts

  • selector

    CSS3 selector string
  • from

    documentContext element. If set to a DOM element, the `selector` will only look for descendants of this DOM Element.

Code

<div id="element_id">
    <p id="a" class="small">
    A text sample with a <span>span</span> and a <a href="#">link</a>.
    </p>
    <p id="b" class="small">
    Another text paragraph. 
    </p>
</div>
<script>

var elmA = Ink.s('#element_id');  
// "div" with id "element_id"

var elmB = Ink.s('#element_id > p');  
// <p> with id "a"

var elmC = Ink.s('.noclass'); 
// null 

var elmD = Ink.s('a', Ink.i('#a')); 
// <a> found in element with id "a" 

</script>

.setPath(key, rootURI) method

Sets the URL path for a namespace.
Use this to customize where requireModules and createModule will load dependencies from.
This can be useful to set your own CDN for dynamic module loading or simply to change your module folder structure

Accepts

  • key

    Module or namespace
  • rootURI

    Base URL path and schema to be appended to the module or namespace

Example

                 Ink.setPath('Ink', 'http://my-cdn/Ink/');
                 Ink.setPath('Lol', 'http://my-cdn/Lol/');
            
                 // Loads from http://my-cdn/Ink/Dom/Whatever/lib.js
                 Ink.requireModules(['Ink.Dom.Whatever'], function () { ... });
                 // Loads from http://my-cdn/Lol/Whatever/lib.js
                 Ink.requireModules(['Lol.Whatever'], function () { ... });
            

.ss(selector, [from]) method

Alias for Ink.Dom.Selector

Using sizzle-specific selectors is NOT encouraged!

Accepts

  • selector

    CSS3 selector string
  • from

    documentContext element. If set to a DOM element, the `selector` will only look for descendants of this DOM Element.

Code

<div id="element_id">
    <p id="a" class="small">
    A text sample with a <span>span</span> and a <a href="#">link</a>.
    </p>
    <p id="b" class="small">
    Another text paragraph. 
    </p>
</div>
<script>

var aElmA = Ink.ss('#element_id'); 
// [object HTMLDivElement] => array with "div" with id "element_id"

var aElmB = Ink.ss('#element_id > p');  
// [[object HTMLParagraphElement],[object HTMLParagraphElement]] with id "a"

var aElmC = Ink.ss('.noclass'); 
// [] 

var aElmD = Ink.ss('.small', document.body); 
// Found all elements with class .small in document.body context 

</script>

.warn() method

Calls native console.warn if available.

Accepts

  • more...

    Arguments to be evaluated

Ink.warn() is an alias to console.warn() when it is available.

Code

function myFunc(a, b) {
    if(!a || !b) {
        Ink.warn('Missing arguments');
    }
    /* ... */
}
myFunc('a');
myFunc(null, 'b');

.VERSION attribute

{String}