Home Java Structure your Javascript with Dojo

Structure your Javascript with Dojo

You use Javascript to animate your website, but your code lacks of structure. Your JavaScript functions are scattered in

Where "dojo.js" is the main page of the Javascript framework. Simply edit the path to the dojo folder according to your current installation!

That's it! Dojo is now ready for use on your site!

How to use the framework?

The dojo.addOnLoad() method: This method is called when the site us loaded. To end the session simply use the dojo.addOnUnload() method, upon closing the website.

Simply place in the home page of your site a JS script calling this method:

Here below, you will learn how to create a Javascript class via Dojo, using the "Application" class.

Start by creating a "Application.js" file.

To illustrate its use, let's pretend that this class is at the root of the site, in the "mysite" folder, and in the "javascript" subfolder: /mysite/javascript/

Ceating a JS class:

dojo.provide('mysite.javascript.Application'); dojo.declare('mysite.javascript.Application', null, { myFirstArgument: null, mySecondArgument: null, constructor: function(param1, param2) { myFirstArgument = param1; // Class constructor code. }, method1: function(param){ }, method2: function(){ } });

Here we see several things:

The dojo.provide function is called, as parameter we used the path to the class file. This allows Dojo "know" that the Application class exists.

The dojo.declare function is called, in which the code for the Application class is found. This method takes three parameters: the classpath a boolean the content of the class, namely: the attributes of classes, initialized to "null" and followed by a comma. the first method: the constructor, which may or may not have parameters. The other class method (optional). Finally braces and closing parentheses of the method stated.

Each attribute and method is followed by a comma to separate it from other, except the last.

As example:

dojo.provide ('monsite.javascript.Application'); dojo.declare ('monsite.javascript.Application', null, { _user: null, constructor: function (userParam) { this._utilisateur = userParam; } start: function () { alert (this._utilisateur); } });

Specifically, here we will create the Application class with a string as parameter, pass the parameter attribute, and then call a method "start ()" which will display this string.

Back to dojo.addOnLoad. Here we will create an instance of our application class and display a specific string.

The code is as follows:

The steps are:

  • Java

LEAVE A REPLY

Please enter your comment!
Please enter your name!