Spot the web RSS 2.0
# Monday, March 03, 2008

Object oriented programming has been around for quite some time and was made popular by C++ back in the day. Nowadays, even web scripting languages support the paradigm. JavaScript does not have true OO but allows you to use the design pattern in your code. Today, we will dive into using object oriented programming with the popular JavaScript framework Prototype.

Prototype makes it easy to declare your own objects by using the "Class.create()" method:

  1. var sampleObject = Class.create();  


Once you do that you can start writing your class specific methods and properties inside the "prototype" object:

  1. sampleObject.prototype = {   
  2. }  


To declare private properties you simply specify the name of the property followed by a colon and the value:

  1. sampleObject.prototype = {   
  2.     linkIDs: ['mainPageLink''cdmScreenLink''adminLink''helpLink'],   
  3.     statusMessage: '',   
  4.     currentLinkID: 'myLink'  
  5. }  


The important thing to remember is that each property needs to be separated from the next by a comma. As shown above, property values can be a array, a number, a string but cannot be empty value. While:

  1. currentLinkID: 'myLink',  


is valid while


is not.

Declaring your own functions is not any different. Before we look into functions however, there is one function that requires special attention: the "initialize" function:

  1. initialize: function() {   
  2. }  


The initialize function is what JavaScript calls automatically when you create an instance of your object. If you are familiar with OO, this function is the constructor of your object. Any setup and initial requirements for using your object should be done in here.

So to get back to regular functions, they are declared in the format functionName: function() {} as in:

  1. doSomething: function() {   
  2. }  


So far your object should like like this:

  1. var sampleObject = Class.create();   
  2. sampleObject.prototype = {   
  3.     linkIDs: ['mainPageLink''cdmScreenLink''adminLink''helpLink'],   
  4.     statusMessage: '',   
  5.     currentLinkID: 'myLink',   
  6.     initialize: function() {   
  7.     },   
  8.     doSomething: function() {   
  9.     }   
  10. }  


Big deal right, including that in your html page and/or a separate JavaScript file does not do anything for you. The next step in making it of any use is to actually create an instance of the object like so:

  1. var sampleObjectInstance = new sampleObject();  


Creating an instance of the object automatically calls all your code inside the "initialize" function. Here, a good practice is to wrap the creation of your object inside the windows load or dom:loaded (Prototype v1.6) event like:

  1. Event.observe(window, 'load'function() {   
  2.     var sampleObjectInstance = new sampleObject();   
  3. });  


Or

  1. document.observe("dom:loaded"function() {   
  2.     var sampleObjectInstance = new sampleObject();   
  3. });  


To expand on using properties inside your object, whenever you want to access a property such as "currentLinkID", you have to prefix it with "this" as in:

  1. this.statusMessage = 'Who Am I?';  


That is because inside your object's function, without "this", the code does not know about the property. The same applies to using function so you cannot simply called the "doSomething" function with:


but instead if you have to use:

  1. this.doSomething();  

 


This can get a little more complicated when it comes to using event listeners inside your code. Let me elaborate. To tie an event observer that will call the "doSomething" function when a users clicks the link with ID 'myLink', you would usually do:

  1. $(this.currentLinkID).observe('click'this.doSomething);  


While that will work, if you try to access any class properties (such as "statusMessage") inside the "doSomething" function, you will get "undefined" for their values. That is because, again as pointed out above, the function is not aware that it belongs to an object so it does not know that the object has properties. The remedy is simple, simply append .bind(this) to the function when it is tied to the event as in:

  1. $(this.currentLinkID).observe('click'this.doSomething.bind(this));  


A similar approach needs to be applied when using the prototype built-in Ajax object. If you want to tie your custom functions to the "onFailure", "onComplete" or "onSuccess" functions, you need to use the "bindAsEventListener" function:

  1. onSuccess: this.showContent.bindAsEventListener(this)  


"Bind" also needs to be used whenever you employ the "each" construct as described in Gotcha with Prototype.Bind and Arrays

Below is the full class:

  1. var sampleObject = Class.create();   
  2. sampleObject.prototype = {   
  3.     linkIDs: ['mainPageLink''cdmScreenLink''adminLink''helpLink'],   
  4.     statusMessage: '',   
  5.     currentLinkID: 'myLink',   
  6.     initialize: function() {   
  7.         this.statusMessage = 'Who Am I?';   
  8.   
  9.         $(this.currentLinkID).observe('click'this.doSomething.bind(this));   
  10.     },   
  11.     doSomething: function() {   
  12.         alert(this.statusMessage);   
  13.   
  14.         new Ajax.Request(   
  15.             $(this.currentLinkID).href,   
  16.             {   
  17.             method: 'get',   
  18.             onSuccess: this.processContent.bindAsEventListener(this),   
  19.             evalScripts: true  
  20.             }   
  21.         );   
  22.     },   
  23.     processContent: function(request) {   
  24.     }   
  25. }   
  26.   
  27. Event.observe(window, 'load'function() {   
  28.     var sampleObjectInstance = new sampleObject();   
  29. });  


To call the functions of the sampleObject from outside you would simply do:

  1. sampleObjectInstance.doSomething();  

While you can access it's properties with the syntax:

  1. alert(sampleObjectInstance.statusMessage);  


That concludes the basic guide to using object oriented programming with Prototype.

Monday, March 03, 2008 10:10:37 AM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
AJAX | Javascript | Programming
# Thursday, February 28, 2008

Over my course of .NET development, I have compiled a list of essential free tools for .NET applications. This is not a the alpha or the omega of tools, just a short list that I feel is essential.

  1. SharpDevelop

    http://www.icsharpcode.net/OpenSource/SD/Download
    An open source IDE for .NET. Check out the full feature tour.


  2. Visual Web Developer Express Edition

    http://www.microsoft.com/express/vwd
    Stripped down version of Visual Studio that allows you to write .NET web applications.


  3. TortoiseSVN

    http://tortoisesvn.net/downloads
    There is no better Subversion client for Windows. You need this if you are going to use VisualSVN with Visual Studio.


  4. NAnt

    http://nant.sourceforge.net
    .NET based automation tool that has many built in tasks but could be extended with custom code written in any .NET language.


  5. Snippet Compiler

    http://www.sliver.com/dotnet/SnippetCompiler
    Snippet compiler is a small tool to write and execute small chunks of .NET code without creating a Visual Studio project.


  6. .NET Reflector

    http://www.aisto.com/roeder/dotnet
    Reflector is the class browser, explorer, analyzer and documentation viewer for .NET. Reflector allows to easily view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL.


  7. Microsoft SQL Server Management Studio Express

    http://www.microsoft.com/downloads/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796&displaylang=en
    Tool for database administration and development from Microsoft


  8. Quest Comparison Suite for SQL Server

    http://www.quest.com/Comparison-Suite-for-SQL-Server
    Compare and synchronize database schema and data


  9. XYPlorer

    http://www.xyplorer.com
    Awesome file manager. The older version is completely free.


  10. Convert C# to VB.NET

    http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx
  11. NAnt Add-In

    http://www.netlogics.ch/devcenter/display/NLC/NAntAddin
    Visual Studio add-in for NAnt integration


  12. NUnit Add-In

    http://www.netlogics.ch/devcenter/display/NLC/NUnitAddin
    Visual Studio add-in for NUnit integration
Thursday, February 28, 2008 2:53:42 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | Microsoft | Programming | Visual Studio
# Monday, February 25, 2008

At a fundamental level it's important to understand how JavaScript timers work. Often times they behave unintuitively because of the single thread which they are in. Let's start by examining the three functions that we have access to with which to construct and manipulate timers.

  • var id = setTimeout(fn, delay); - Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
  • var id = setInterval(fn, delay); - Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
  • clearInterval(id); - Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.

In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution. This is best demonstrated with a diagram, like in the following:


(Click to view full size diagram)

There's a lot of information in this figure to digest but understanding it completely will give you a better realization of how asynchronous JavaScript execution works. This diagram is one dimensional: vertically we have the (wall clock) time, in milliseconds. The blue boxes represent portions of JavaScript being executed. For example the first block of JavaScript executes for approximately 18ms, the mouse click block for approximately 11ms, and so on.

Since JavaScript can only ever execute one piece of code at a time (due to its single-threaded nature) each of these blocks of code are "blocking" the progress of other asynchronous events. This means that when an asynchronous event occurs (like a mouse click, a timer firing, or an XMLHttpRequest completing) it gets queued up to be executed later (how this queueing actually occurs surely varies from browser-to-browser, so consider this to be a simplification).

To start with, within the first block of JavaScript, two timers are initiated: a 10ms setTimeout and a 10ms setInterval. Due to where and when the timer was started it actually fires before we actually complete the first block of code. Note, however, that it does not execute immediately (it is incapable of doing that, because of the threading). Instead that delayed function is queued in order to be executed at the next available moment.

Additionally, within this first JavaScript block we see a mouse click occur. The JavaScript callbacks associated with this asynchronous event (we never know when a user may perform an action, thus it's consider to be asynchronous) are unable to be executed immediately thus, like the initial timer, it is queued to be executed later.

After the initial block of JavaScript finishes executing the browser immediately asks the question: What is waiting to be executed? In this case both a mouse click handler and a timer callback are waiting. The browser then picks one (the mouse click callback) and executes it immediately. The timer will wait until the next possible time, in order to execute.

Note that while mouse click handler is executing the first interval callback executes. As with the timer its handler is queued for later execution. However, note that when the interval is fired again (when the timer handler is executing) this time that handler execution is dropped. If you were to queue up all interval callbacks when a large block of code is executing the result would be a bunch of intervals executing with no delay between them, upon completion. Instead browsers tend to simply wait until no more interval handlers are queued (for the interval in question) before queuing more.

We can, in fact, see that this is the case when a third interval callback fires while the interval, itself, is executing. This shows us an important fact: Intervals don't care about what is currently executing, they will queue indiscriminately, even if it means that the time between callbacks will be sacrificed.

Finally, after the second interval callback is finished executing, we can see that there's nothing left for the JavaScript engine to execute. This means that the browser now waits for a new asynchronous event to occur. We get this at the 50ms mark when the interval fires again. This time, however, there is nothing blocking its execution, so it fires immediately.

Let's take a look at an example to better illustrate the differences between setTimeout and setInterval.

  setTimeout(function(){
    /* Some long block of code... */
    setTimeout(arguments.callee, 10);
  }, 10);
 
  setInterval(function(){
    /* Some long block of code... */
  }, 10);

These two pieces of code may appear to be functionally equivalent, at first glance, but they are not. Notably the setTimeout code will always have at least a 10ms delay after the previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10ms regardless of when the last callback was executed.

There's a lot that we've learned here, let's recap:

  • JavaScript engines only have a single thread, forcing asynchronous events to queue waiting for execution.
  • setTimeout and setInterval are fundamentally different in how they execute asynchronous code.
  • If a timer is blocked from immediately executing it will be delayed until the next possible point of execution (which will be longer than the desired delay).
  • Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).

All of this is incredibly important knowledge to build off of. Knowing how a JavaScript engine works, especially with the large number of asynchronous events that typically occur, makes for a great foundation when building an advanced piece of application code.

Monday, February 25, 2008 5:01:18 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
Javascript | Programming
Navigation
Archive
<March 2008>
SunMonTueWedThuFriSat
2425262728291
2345678
9101112131415
16171819202122
23242526272829
303112345
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Guy Levin
Sign In
Statistics
Total Posts: 63
This Year: 0
This Month: 0
This Week: 0
Comments: 14
Themes
All Content © 2010, Guy Levin