5 Minute JavaScript #6 Namespaces

Last post we noticed that variables can easily be attached to the global scope. This isn’t a good thing. The more variables are linked to the global scope the more chance you have creating conflicts.

A great way to reduce the impact of your code on the global object is to define namespaces. We do this by creating one global object that we extend with extra modules which on their turn can be extended with new functionality and properties.

// Initialize this first before any other code
var Application = {};

// might be in another file for example module1.js
Application.module1 = {
	calculate: function () {},
	redirectTo: function () {}
};

// might be in another file for example module2.js
Application.module2 = {
	calculate: function () {},
	doSomething: function () {}
};

// In application
Application.module1.calculate();
Application.module2.calculate();

By defining the Application namespace (and the two module ‘packages’) we have no conflict between the two difference calculate functions. We also know at all times what function we are calling from which subproject or module.

This is a first step into creating frameworks, but it’s not the best solution. Most daily JavaScript users know this pattern and are using it to reduce conflicts. However, we know that in JavaScript functions are very important, so maybe we are able to improve this solution by throwing in some functions?

Java 8 and Spring 4

On March 27, 2014, the Spring community was happy to announce the Spring Framework 4.0.3. The reason why is that it was the first release of the Spring Framework with Java 8 support. Since then, the Spring team worked very hard to provide major updates for the Spring Framework to be even more supportive towards Java 8. As of September 4, 2014, the Spring Framework 4.1 has arrived with even more support towards the Java community.

Lambda support in Spring 4.0

A good example to show the Lambda support in Spring is the JdbcTemplate class. If we would like to obtain female employees and map them as an instance of type Employee, we could do something like this:

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

jdbcTemplate.query("SELECT first_name, last_name FROM employee WHERE gender = ?",
                   ps -> {ps.setString(1, "FEMALE");},
                   (rs) -> new Employee(rs.getString(1), rs.getString(2)));

The complete list of Spring 4.0 features can be found here.

Optional for injection points and MVC handler parameters in Spring 4.1

As of Spring 4.1, JDK 1.8’s java.util.Optional is now supported for @RequestParam, @RequestHeader, and @MatrixVariable controller method arguments. This means that while using Java’s Optional, you make sure that parameters are never null.

The following example shows an example of a @RequestParam in Spring MVC prior to version 4.1.

@RequestMapping(value="/iadvise")
public String findEmployee(@RequestParam(value = "employeeId") String employeeId) {
  StringBuilder response = new StringBuilder("id: ");
  response.append(employeeId.toUpperCase());
  return response.toString();
}

When calling the findEmployee method without providing an employeeId, the method will return a NullPointerException. This can be solved by Java’s Optional element.

@RequestMapping(value="/iadvise")
public String findEmployee(
  @RequestParam(value = "employeeId") Optional<String> employeeId){
  StringBuilder response = new StringBuilder("id: ");
  employeeId.ifPresent(value -> response.append(employeeId.toUpperCase()));
  return response.toString();
}

The same result can be achieved for the @RequestHeader, and @MatrixVariable annotations.

The complete list of Spring 4.1 features can be found here.

5 Minute JavaScript #5 Globally Implied

JavaScript uses the var-statement to declare variables and bind them to a scope. But this statement isn’t mandatory. In JavaScript you are allowed to define a value without this statement. When you do not use the var-statement, the variable will be added to the Global Object (see previous post).

function f () {
	x = 1;
}

Whenever we execute f we won’t bind the x variable to f, instead we will define a new property named x on the global object. So, it definitely seems like a good plan to always use the var statement! But sometimes you can just forget to define the value before using it…

function f () {
    var x;  // (= undefined)
    /* some code */
    if (/* something is true */) {
	  x = 'something';
    } else {
	  x = 'something else';
    }	

    return x;
}

If in this example you had forgotten to declare x before using it (in the if-statement), you would have declared x globally. Since these kinds of issues are hard to detect, you will need to be disciplined in your variable declaration because JavaScript won’t force you to do it.

When you define x without any value, you are actually saying “in this scope there is a variable with name x, but its value is undefined”. The next time you will attach a value to the variable you won’t need to use the var-statement.

Export/Import Apex applications in SQL Developer

Using SQL Developer to export or import an Apex application is not only easy, it’s also fast!

Export

To export, follow these steps:

Open the connection to the schema where you’re application is located and search for the “Application Express” directory:

image_1

Right click on the application you want to export and choose “Quick DDL” > “Save to File…”:

image_2

When done, you’ll have the same file as you would have exported from the Apex GUI.

 

Import

To import an application, right click on the “Application Express” directory, and choose “Import Application”. You can also right click on an existing application; the next steps are the same.

Follow the wizard. When this screen appears, you can choose to do a number things:

image_3

 

  • Auto Assign Application ID
  • Use the application ID from the export
  • Specify New ID

When the ID that you want to use is already assigned in your workspace, don’t forget to check the “Overwrite” checkbox.

At the end of the wizard you see the progress of the installation:

image_4

When finished, you’re application is up and running.

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","");