Stroep

Just a collection of random works – Mark Knol

Tag Archives: Javascript

This article is some training for your JavaScript skills. I love Actionscript , and I am also starting to like JavaScript. However, coding in JavaScript feels like Actionscript 1.0. It’s a pity there aren’t decent editors, especially if you want to write object-oriented-code, which is possible with JavaScript . At the moment I think VisualStudio is the best JavaScript editor, but I really wish there was a tool for JavaScript like FlashDevelop (a clean editor for Actionscript projects) with great intellisense, code completion and snippets etc. But we should not focus on tools, lets focus on the language and get the most out of it. HTML5 is an hot topic today, and it seems using JavaScript is an important part of it, so why not learn more of it? I have seen some stunning HTML5 examples over the last year. As a developer it is very interesting to see how others code JavaScript. By the way; Personally I find it very funny to see how JavaScript has changed it’s ‘image’. Some of us remember the good days in Netscape. JavaScript was .. *kuch* not fast and associated with ugly rainbow mouse pointers and aggressive popup screens. Now it is associated with HTML5, which is supposed to be the future and it will be bright ;) I refuse to put my opinion about this topic here.
I think the ‘image’ of JS has slowly changed after great frameworks like jQuery have reached the developers. jQuery is awesome, I advice to use jQuery as default in all sites/apps.

Anyway, there are (ofcourse) some techniques to code like Actionscript in JavaScript. These snippets have helped me to understand object oriented JavaScript. For too long I did not even tried to learn what was possible with JavaScript because I thought it was a very limited language. Maybe some information is outdated; I am still learning, so please share your feedback.

Object oriented javascript

In javascript it is possible to create classes, public and private vars, getters/setters and there are even constructors. A function could be seen as a class. This is a bit strange at first, but if you use it for a while you will understand. Now lets create our own class right now.

Lets port some stuff of this Color Class to javascript. It has private vars and public functions.

Declare classes

Defining classes is as easy as defining functions, because it is almost the same. After creating an function, you could already make some instances of it. The example below creates a Color class with a public variable called value. After that we create 2 instances of the Color class with some other values.

Note: I use the same code conventions as Actionscript: Classes should be UpperCased, functions/vars should be lowerCased and constants should be FULL_CAPS. Oh and since javascript looks like as1.0, I sometimes use an underscore before private vars :P

function Color( value )
{
    this.value = value || 0;
    alert("Color created with value: " + value)
}

var myRedColor = new Color(0xFF0000); // create instance of Color  (a red one)
var myOrangeColor = new Color(0xFFCC00); // create instance of Color  (an orange one)
alert( myRedColor.value );
alert( myOrangeColor.value );
 

Public / Private

In actionscript it is very useful to use encapsulation, which is a mechanism for restricting access to other objects. The previous+following example should work in all browsers. The difference between public and private vars/functions in javascript can be declared like this:

function Color( value )
{
    // public variable
    this.value = value || 0xFFFFFF; // set default value to 0xFFFFFF for parameter if it isn’t defined

    // private variable
    var _name = "test";

   // public function
   this.getRandomColor = function( )
  {
     return Math.random() * 0xFFFFFF;
  }

  // private function
  function getNiceColor()
  {
     return 0xffcc00;
  }
}

// create instance of Color
var color = new Color(0xFF0000);
alert( color.value ); // returns red color
alert( color.getRandomColor() ); // returns random color

// not possible :
alert( color.getNiceColor() ); error in console; property does not exist, because function is private.
alert( color._name ); // error in console; property does not exist, because variable is private.
 

I think with this principles (maybe in combination with namespaces, see below) you can create clean javascript code.

Packages > Namespaces

Now before using classes in javascript I had some conflicts with function and variable names because there were unwanted duplicates. I have written a little helper tool to use namespaces. It helps to prevent those conflicts. Now it looks more like Actionscript 3, only there is no such thing like ‘imports’. This snippet works in all browsers.

/// create namespace like ‘com.yourcompany.projectname’
function Namespace(namespace)
{
    var parts = namespace.split(".");
    var root = window;
    for(var i = 0; i < parts.length; i++)
    {
        if(typeof root[parts[i]] == "undefined")
        {
            root[parts[i]] = {};
        }
        root = root[parts[i]];
    }
}

// creating my own namespace here
Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function(value) // create class inside package
{
  this.value = value || 0xFFFFFF;
}

var myRedColor =  new nl.stroep.utils.Color(0xff0000);
alert(myRedColor.value);
 

Getters and Setters

Now it is possible to use getters and setters. NOTE (!): Ofcourse this method does not work in IE, so this is pointless but also a bit cool to see how far we could go. Anyway there are 2 ways to define them. Read more about it here. I think the __defineGetter__ way is better; it looks ugly but you still have access to private objects.

Take a look at this getter/setter declaration example. It’s not as clean as AS3 getters/setters but it works like a charm in my browser.

function Color( value )
{

   /* public getter */
   this.__defineGetter__("value", function()
   {
        alert("getter called; current value: " +value);
        return value;
    });
   
   /* public setter */
   this.__defineSetter__("value", function(val)
   {
        alert("setter called; new value: " +val);
        value = val;
    });
   
   // public variable. For a strange reason I have to put this below the get/set definition.
   this.value = value || 0xFFFFFF;
}

// create instance of Color
var color = new Color(0xFF0000);
color.value; // getter
color.value = 0xff0000; // setter
 

Constants

Javascript has a const too, you could use it instead of var. Ofcourse this is not implemented in IE, so it is also pretty pointless to use.

Mix them all

Now lets use namespaces, getters/setters and private/public variables and functions together.
This is a simplified ported version of this Color Class.
With this class you can modify the red,green and blue channels of a color individually. In the original class it is possible to lighten/darken the color too, but for this post I left these functions, because this only illustrates the possibilities of nice OO javascript.

Namespace("nl.stroep.utils");
nl.stroep.utils.Color = function( color )
{   
    /* PUBLIC FUNCTIONS */
   
    this.grayscale = function( val )
    {
        val = val || 0;
        if (val < 0){ val = 0 }
        if (val > 255) { val = 255 }
       
        return (val << 16) | (val << 8 ) | val;
    }
   
    /* PRIVATE FUNCTIONS */
   
    function limit( val, lowerLimit, upperLimit )
    {
        if (val < lowerLimit){ return lowerLimit }
        if (val > upperLimit) { return upperLimit }
        return val;
    }
       
    /* PUBLIC GETTER FUNCTIONS */
   
    this.__defineGetter__("value", function()
    {
        return (_red << 16) | (_green << 8 ) | _blue;
    })
   
    this.__defineGetter__("red", function()
    {
        return _red;
    })
   
    this.__defineGetter__("green", function()
    {
        return _green;
    })
   
    this.__defineGetter__("blue", function()
    {
        return _blue;
    })
   
    /* PUBLIC SETTER FUNCTIONS */
   
    this.__defineSetter__("value", function(val)
    {
        _red  = val >> 16 & 0xFF; // red
        _green  = val  >> 8 & 0xFF; // green
        _blue = val & 0xFF; // blue
       
        _value = val;
    })
   
    this.__defineSetter__("red", function(val)
    {
        _red = val;
        _red = limit( _red, 0, 255 );
    })
   
    this.__defineSetter__("green", function(val)
    {
        _green = val;
        _green = limit( _green, 0, 255 );
    })
   
    this.__defineSetter__("blue", function(val)
    {
        _blue = val;
        _blue = limit( _blue, 0, 255 );
    })
   
    /* PRIVATE VARIABLES */
    var _value = color;
    var _red;
    var _green;
    var _blue;
   
    /* PUBLIC VARIABLES */
    this.value = _value;
   
};
 

With this javascript class, you could use it like this:

var color = new nl.stroep.utils.Color(0xFFCC00) // define orange.
color.green = 0; // remove green.. now it is red..
color.blue = 255; // add some blue.. now it is purple..
alert(color.value.toString(16)) // alerts FF00FF and that is purple.
 

Hope you enjoyed this article. Feel free to share or comment.

Tagged with , , , , .

With Flex you can create applications. So, why not start creating a very simple application, like a calculator?

How does a calculator work, in my opinion? Simple: it just evaluates a string. But how can we evaluate a simple string like “1+1″ in AS3? I think we can’t, because eval() isn’t supported in actionscript 3. So I search on google, and found some solutions for it. But nothing really satisfied me. I don’t want to use PHP or another serverside script for evaluating strings, do you? So why not using a client side script, like javascript?

I want to share how I did this to you, and also the process of creating a calculator.

Setup a new project
I use FlashDevelop for Flex applications. Create a new project ( Menu > Project > Flex 3 project). Open the main.mxml file in the src-folder. Make shure it is set to ‘always compile’ (the green icon). Let’s add some data:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
   
    <mx:Panel title="Calculator" width="300" paddingLeft="30" paddingBottom="30" paddingRight="30" paddingTop="30" >
       
        <mx:Text text="input"/> <mx:TextInput id="input" />
       
            <mx:Button click="output.text = input.text" label="calculate"  />   
           
        <mx:Text text="output"/> <mx:TextInput id="output" />
       
    </mx:Panel> 
   
</mx:Application>
 

What did we just created? Check out the code and press ctrl-enter to run the application. We have a container panel, an input field and an output field. Press the button and the text from the input will be shown in the output textfield. Great, isn’t it?

To be real; if you never ever used Flex, this ÍS great. How much time did we spend to create a simple interface like this? We just used 5 tags, and it already is an application.

Basic layout of a flex calculator

Create a html document
We need html, because we need to communicate between the swf and javascript.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>My calculator</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>

<object type="application/x-shockwave-flash" data="flexproject.swf" width="800" height="600">
    <param name="movie" value="flexproject.swf" />
</object>      
   
</body>
</html>

No, nothing special, just another html file. It’s better to use swfObject for embedding flashfiles, but that’s not what this tutorial is about. Save the html document in the same directory as the .swf file (in my case: in the bin folder)


Let’s calculate
We need our flex application to calculate! Let’s add some script (actionscript) to the application. Put this somewhere between the mx:Application tag:

    <mx:Script>
        private function eval( str:String ):String
        {
            return ExternalInterface.call ( "eval", str );
        };
    </mx:Script>

With externalinterface we can communicate between flash and javascript. We have just created an internal function named ‘eval’. This is going to be the function for the calculator. This function uses a string. Externalinterface calls the javascript function “eval” with the parameter from the function and returns that string. This is the magical trick in this tutorial, so make shure you get this point ;) You have created an actionscript function called eval, that uses the eval function from javascript. I think this is a really global function, so you can use it in other AS3 projects too.

Alright, let’s edit the calculate-button like this:

<mx:Button click="output.text = eval( input.text )" label="calculate"  />

Now build the project and open the html document we have created earlier. Note: from now on just build your project en hit refresh on your browser. You can’t calculate within the FlashPlayer, because javascript calculates for us, remember?

Now we have a very simple calculator.

Let’s make it better. We don’t need two textfields (input / output), but we need one uneditable field. I choose to use a mx:Label, please don’t ask me why. We also need buttons, just like the windows calculator. The button need to add text to our label-field. For that, let’s add a new AS3-function to the mx:Script tag:

private function addText( str:String ):void
        {
            input.text += str;
        }

This is straight forward. When we call the function, the input field adds text that is passed by the function. I used a function for this, because we are going to use it more than 1 time. You could use this inline in the buttons, but we need a lot of buttons. Maybe later we would edit this, so then we only have to edit the function, instead of copy/paste this multiple times.
Make a button to test it. Add somewhere a button like this:

<mx:Button click="addText( ‘add me’ )" label="click me" />

Test the movie. It works! You can delete the button.

Now, let’s add the other buttons. I used a mx:Panel with an absolute layout, so we can use x and y positions. I changed the layout a bit, and created something this: (this also is the the full code)

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" themeColor="#ff0000" backgroundColor="#333333" barColor="#ffcc00">
   
    <mx:Panel title="Calculator" width="300" paddingLeft="30" paddingBottom="30" paddingRight="30" paddingTop="30" >
       
        <mx:Label id="input" fontSize="30" text=""  />
           
        <mx:Panel borderStyle="none" label="Calculator" width="100%"  layout="absolute" >
            <mx:Button click="addText( ’1′ )" label="1" x="0" y="0" />
            <mx:Button click="addText( ’2′ )" label="2" x="50" y="0"   />
            <mx:Button click="addText( ’3′ )" label="3" x="100" y="0"  />
            <mx:Button click="addText( ’4′ )" label="4" x="0" y="30"  />
            <mx:Button click="addText( ’5′ )" label="5" x="50" y="30"  />
            <mx:Button click="addText( ’6′ )" label="6" x="100" y="30"  />
            <mx:Button click="addText( ’7′ )" label="7" x="0" y="60"  />
            <mx:Button click="addText( ’8′ )" label="8" x="50" y="60"  />
            <mx:Button click="addText( ’9′ )" label="9" x="100" y="60"  />
            <mx:Button click="addText( ’0′ )" label="0" x="0" y="90"  />
            <mx:Button click="addText( ‘+’ )" label="+" x="0" y="120"  />
            <mx:Button click="addText( ‘-’ )" label="-" x="50" y="120"  />
            <mx:Button click="addText( ‘*’ )" label="x" x="100" y="120"  />
            <mx:Button click="addText( ‘/’ )" label="/" x="150" y="120"  /> 
            <mx:Button click="input.text = ”" label="CE" x="0" y="150" width="190"  /> 
            <mx:Button click="input.text = eval( input.text )" label="="  height="110" x="150" y="0" /> 
        </mx:Panel>    
       
    </mx:Panel>
   
    <mx:Script>
        private function eval( str:String ):String
        {
            if ( ExternalInterface.available )
            {
                return ExternalInterface.call ( "eval", str );
            }
            else
            {
                return "Unavailable"
            }
        }      
        private function addText( str:String ):void
        {
            input.text += str;
        }
    </mx:Script>
   
</mx:Application>
 

What are you waiting for? Run the application :D

Layout of your flex calculator

Well, that looks different! Take a look at the code. We have created buttons like 0-9, and some math signs. This buttons don’t calculate, they just add text. We have changed the ‘calculate’-button’ to an ‘=’ sign, and we have a clear button.

I think this is a start of using Flex and building a calculator. I’m learning Flex too, so correct me if i’m doing something wrong.

Tagged with , , , , .