5 Minute JavaScript #4 Global Object

Now that we know how to create scopes and how to bind variables to them, we should also be aware of JavaScript’s global object. Whenever we declare a variable with the var-statement, the variable will be bound to the nearest scope. But what happens when there is no scope? It needs to be attached to something, right?

<code>
	var x = 1;
<code>

In this example, there is no function to which x can be bound. Therefore x gets added to the global object. Being part of the global object means that the value is accessible from everywhere. This might sound exciting, but you have to know that this can cause a lot of problems. A filthy global object is a ticking time bomb, waiting to explode and become conflict issues.

Some JavaScript create multiple script files containing functions and include them in their HTML-page based on some back-end logic.

script-module1.js

function calculate(){}
function redirectTo(){}

script-module2.js

function calculate(){}
function doSomething(){}

Imagine these files to be part of two different modules, designed by two different teams and combined into one application. If these two files get included into one HTML-file, a conflict rises for the calculate function and unexpected behaviour is possible. This is because functions are also values and we know that values that aren’t bound to a scope are part of the global object.

So although these functions are in different files, they can be combined into one HTML-page and that’s when conflict issues tend to rise. These conflicts are sometimes very hard to find (especially in large code bases).

If you want to know what’s defined in the global object, you can always check the window object (only in browsers, NodeJS works differently). This object contains all native JavaScript functions and all the functions/variables you have defined globally.

5 Minute JavaScript #3 var-statement

In our previous post we discussed the importance of functions and scopes. The var-statement is narrowly linked to these concepts. Most Object-Oriented languages are statically typed. This means that you will need to declare the type of the variable you want to define before compiling. JavaScript however is dynamically typed and every value is defined with a var-statement.

var number = 1;
number = "Now it’s a string";

If the type of a variable can change, it gets tricky. You should never do that, but JavaScript allows it.

Back to the var statement. Using this statement is just like saying “name this value and bind it to the nearest scope”. An example:

function f () {
    var variable = "value";
}

The var-statement will make the “value” with the name ‘variable’ accessible in the context (scope) of the function f (because this is the first scope it encounters).

It’s important to know that only functions can create scopes. So, visibility of a variable will only be bound to a function. This means that functions become increasingly more important in JavaScript. Check out our previous blog post if you want to know a little more about functions and scopes.

Triggering Dynamic actions from javascript code in APEX

Since APEX 4.0, dynamic actions have made our lives easier. But sometimes they feel a little restrictive in what you can do with them. Executing them upon the successful completion of another dynamic action, for example, or forcing a dynamic action to fire, triggered by something that happened in your javascript code.

APEX 4.2

Since APEX 4.2, there is a way to do this easily.

We start by creating the application process that needs to be triggered. It is important that you choose the event type “Custom”, and give it a name.

da1

To keep the example simple, I made a true action executing some javascript and printing it to a region on the page.


$('#dynamicactionresult > .uRegionContent').html('Dynamic action triggered successfully');

The hardest part is over now. All that’s left to do, is trigger the dynamic action from javascript. This can be done with the following piece of code:


$.event.trigger('TriggerMe');

Where TriggerMe references the name of your “custom event”.

Older versions of APEX 4.x

The above only works from APEX 4.2. However, for the older versions of APEX 4 there is a workaround!

First, we make a hidden page item, allow it to be accessed by javascript and set protected to “No”.

da2

Next, we create a dynamic action that triggers on change of this item, executing some javascript code as mentioned before.

da3

Finally, we trigger this application process by forcing a change-event on the page item. This can be done with the following piece of code.

apex.event.trigger($("#P1_DYNAMIC_ACTION_TRIGGER"),"change","");

5 Minute JavaScript #2 Scopes

In our last blog post we showed that JavaScript is different from Java when talking about functions. Another difference with regard to these object-oriented language lies in the code scope. Scopes are blocks of code in which a variable is known. It’s a context in which some variables are accessible, others are hidden, destroyed, etc.

In Object-Oriented languages such as Java, everything inside a  { } – pair is confined into a scope. For example:

if (true) { String s = "Scoped"; }

System.out.println(s); // s does not exist

In JavaScript however, only variables declared inside a function are scoped. This is a very important difference. When working with if-statements or for-loops, the variables you define there aren’t scoped to the code block, but to the parent function.

function f () { var x = "not accessible outside function f"; }

if (true) { var x = "also available outside the if-statement"; }

for (var i = 0; i < length; i++) { /* code */ }
console.log('i is known outside the for', i);
    

You might think that this is a shortcoming in JavaScript, but it’s not. This way of scoping is used in many functional languages, it’s just another way of thinking.

So when you are thinking about encapsulating properties and variables, remember that you will have to use functions.

5 Minute JavaScript #1 Functions

It’s no secret that functions in JavaScript are first-class citizens. But what does that actually mean? While the name JavaScript suggest a certain similarity with Java, JavaScript is in essence extremely different. In Java, everything revolves around Classes which instantiate into Objects, while in JavaScript the main building block of your application is a function. Also, in JavaScript, everything is an object… even functions!

This is how we define a function in JavaScript:

function functionName (/* parameters */) {
    /* body */
}

While every programmer recognizes this template and might know how functions work, JavaScript allows more than just executing them. For example, you can:

  • store them in variables
  • define them as properties of an object
  • add properties to the function object

In fact, functions in JavaScript are much like objects. They even have native properties and behaviour such as a name property and methods like call or apply.

var example = function myName () {/* body */};
console.log(example.name); // outputs myName

In JavaScript, functions hold great power by being able to pass them along as values (and parameters). However, it doesn’t stop there… functions have even more tricks up their sleeves. Find out in our next blog post.

HTTP/2 server push

HTTP/2 general

In general HTTP/2 is about optimizing server resource usage. This is mainly achieved by using 1 connection between server and client and re-using that connection for all requests/responses for the duration of the session.

This is in sharp contrast with HTTP/1. Where a connection is created, a request is sent, a response is received and the connection is terminated. This is overhead is more or less hidden to the user because multiple connections are used in parallel.

HTTP/2 server push

HTML pages reference many other resources. Using HTTP/1 the client needs to parse the HTML page, identify the referenced resources and fetch them. Every round-trip incurring the connection setup/breakdown overhead.

Using HTTP/2 the server can send these referenced resources to the client before they are needed and because the same connection is used there is no connection setup/breakdown overhead.

Use cases

Pushing page resources before they are needed will make a site/application more responsive to it’s users. But doing this manually for all pages of an application is only going to be feasible for the smallest of applications.

Web/ UI component frameworks may push framework resources that are needed. Multiple approaches can be taken in this space. All framework resources can be pushed or only the resources that are needed based on the components of the framework that are used.

What is available

Since HTTP/2 is a draft spec, it is still early days for HTTP/2. Currently there is no standard Servlet API but that can’t stop us, Jetty already has an experimental API.

Google Chrome Canary has support for HTTP/2 when started with –enable-spdy4 as start parameter.

Firefox has support for HTTP/2 when the network.http.spdy.enabled.http2draft is switched on.

Test case

In order to test server push I’ve taken one of my panoramic vacation photos and sliced it up into 400 parts. This may be a little over the top but as with all tests we want to test the limits.

The test has been executed using 2 web-modules:

  • blog-http1-no-push – containing a servlet on URL /nopush that does not perform any pushes.
  • blog-http2-push – containing a servlet on URL /push that executes server pushes for the image slices.

The blog-http1-no-push web module was deployed to a Jetty server containing only the http, annotations and deploy modules running on port 8080.

The blog-http2-push web module was deployed to a Jetty server containing only the http2, annotations and deploy modules running on port 8443.

Both these setups are available as Docker images:

Both web modules contain a single servlet. The servlets take a rows & columns attribute as parameters. This allows us to control the amount of resources that are contained in the generated page. They also control the amount of resources that are pushed by the blog-http2-push web module.

During testing I did notice that the server sometimes becomes unstable when trying to push all 400 image slices. I’ve contacted the jetty users mailing list, perhaps some additional configuration needs to be set when pushing a lot of resources. I’m waiting for their reply.

How do you use HTTP/2 in code

Initially there was a push method on the Dispatcher class, but while writing this blog the Jetty project deprecated that method and made a PushBuilder available via the Request class.

final Request jettyRequest = (Request) getRequest();

jettyRequest
    .getPushBuilder()
    .push(resourcePath);

Checkout the sources on Github https://github.com/teyckmans/http2-push

Performance difference

In order to have a correct test case I’ve deployed the Docker images in the Google cloud in the us-central1-a zone in order to have real network overhead. Measurements have been taken with cache disabled in Google Chrome Canary using the load number.

HTTP/1 – no push
http://%5Bhost-external-ip%5D:8080/blog-http1-no-push/nopush?rows=5
3.01s (average of 6)

HTTP/2 – push
https://%5Bhost-external-ip%5D:8443/blog-http2-push/push?rows=5
1.51s (average of 6)

Pretty spectacular difference if you ask me.

Do It Yourself

I’ve uploaded the Docker images to the docker hub so you can try it out and experience the difference yourself.
Use the following command lines to run the test web-modules.

HTTP/1 – no push
docker pull teyckmans/blog-http1-no-push
docker run –name blog-http1-no-push-1a -i -t -p 8080:8080 teyckmans/blog-http1-no-push

HTTP/2 – push
docker pull teyckmans/blog-http2-push
docker run –name blog-http2-push-1a -i -t -p 8443:8443 teyckmans/blog-http2-push

Using Apex Authorization schemes in PL/SQL

The problem with using APEX authorization schemes in PL/SQL has been addressed several times in blogs and forums, but we occasionally still get questions  on how to solve this:

I have a page where users with admin roles can modify data and other users can only view it. Hiding the button to save the record is easily done with an authorization scheme:

Capture

However, now I want my items to be displayed as “Read Only” too. There is no option to select your authorization scheme, but Apex wouldn’t be Apex if there hadn’t been an easy solution.

The function “apex_authorization.is_authorized(‘authoutization_scheme’)” does the trick. It will check the authorization scheme and return a boolean. Add a small PL/SQL block in the Read Only-part of your item like this:

Capture

Now your item is read only for persons without the admin role.


Some additional information:

With this function it’s also possible to combine multiple authorization schemes:

IF apex_authorization.is_authorized('isAdmin')
   OR apex_authorization.is_authorized('isWrite')
   OR :P3000_USER = 'TEST' THEN
  RETURN FALSE;
ELSE
  RETURN TRUE;
END IF;

Attention: if you want to use this functionality prior to Apex 4.2, you need to use “apex_util.public_check_authorization“!