Effective JavaScript for Liferay

The State of JavaScript in Liferay

Liferay's Javascript is based on library named AlloyUI that has Yahoo UI framework and bootrstap (starting from version 6.2 underlying. Besides lots of stuff from YUI it has many own improvements and portal specific features. Alloy brings JQuery like API that makes it easier for frontend developers to learn. You can compare and reffer to this at the following url:

Modules & Dependencies

Let's create file named my-form.js in js folder of portlet. First of all, we should enclose our javascript function into anonymous function as it's intended to be used in most of js frameworks. We will use AUI global object function call and functions to load Alloy UI modules that is names use. The second function we call that is named add brings out module to the development pool that allows to rely other code loading only after mentioned in use is loaded

AUI().use('aui-base').add('my-form', function(A) {



We can add it to jsp view code:

<script src="<%=request.getContextPath()%>/js/my-form.js"></script>
<script use="my-form"></script>


Modern JavaScript practices brings some new ideas to frontend developers that helps to get better architechtures for larger apps.

  • Object oriented desingn
  • Functional separation, layered architecture: (MVC etc.), Among usual things Dom operations, configuration are speparated from business logic

So instead of hundreds of functions Alloy withYui introduces Components that allows you to split the code into resusable, logically consistent units. We will create component definition just in our anonymous functon body:

AUI().use('aui-base').add('my-form', function(A) {
    var NS = 'ns';
    var PARAMS = 'params';
    Liferay.Portlet.MyForm = A.Component.create({
        NAME: 'myForm',
        EXTENDS: A.Component,
        ATTRS: {
            ns: {},
            params: {}
        prototype: {
            bindUI: function() {
                var instance = this;
                instance._initSomeFunctionality(instance.get(NS), instance.get(PARAMS));
        _initSomeFunctionality: function(ns, params) {
            var instance = this, someParameter = params.someParameter;
            console.log('someParameter', someParameter);

And now we can load component in a better way with external paramenters

<script use="my-form">
    new Liferay.Portlet.MyForm({
        ns: '<portlet:namespace />',
        params: {
            someParameter: 'someValue'

This components should print parameters from outside when loaded. Configurations options, dom selectors, data values are better to be passed in this way.