Monday, March 9, 2015

HTML Form Elements - Differences in attributes and properties

HTML Form elements are the staple widgets that you come across as a web developer. These are your basic button, text-input field, text area, check-box etc.
But the APIs are not as simple as they seem though, if you are seeing them new.

Lets see why..

The HTML Form elements can be updated by updating the Element attributes and the DOM object properties.

Attributes are available directly on the element
Eg:
<input id ='inputfield' type ='text' value ='foo'>
Here id, type and value are attributes

DOM properties are available via the DOM API on the Element
i.e.
var textInput = document.getElementById('inputfield')
textInput.value is a DOM property

Its nice to see that the property names are consistent with the attribute names(for the most part)

But its confusing that the behavior is not consistent.

Attribute values only represent the initial value
i.e. once a user-interaction changes the state, the attribute values are not representative of the visual,
 whereas DOM object properties can be used to update and query the current state of the element
It has always worked this way and per the spec.
http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-49531485

Here is a fiddle to help understand better
http://jsfiddle.net/deepakanand/sLd65egb/3/

Related bug reports (that have been marked as not bugs)
https://bugzilla.mozilla.org/show_bug.cgi?id=223003
https://bugzilla.mozilla.org/show_bug.cgi?id=327020

Thursday, March 5, 2015

Class style programming in JavaScript: Part 1

JavaScript does not have language support for classes in the same way that Java does[1]
But, JavaScript is a versatile language. It can be tailored to mimic different programming paradigms. The Java-style class-based programming pattern is quite popular. So much so, that there are dedicated modules in frameworks such as Dojo declare[2], Prototype's Class.create and the list goes on. This pattern is also commonly referred to as Object Oriented programming, which I think is a misnomer because it really is more about classes than objects. 
In JavaScript, functions play the role of..well.. plain old functions and also to create class-like entities.For this post, we are interested in the latter. When a function is invoked with the "new" keyword, it returns an object i.e. it acts as a constructor.
Lets look at an example:
1
2
3
4
5
6
7
8
9
var Car = function(numGears){
 this.numGears = numGears;
 this.drive = function(){
   console.log("driving");
 }
};

var myCar = new Car(4);
myCar.drive() //driving
Whoa.. the above type of Car cannot be stopped, because there is no method/mechanism in the Car function to do that.
Lets add a stop() method to that
1
2
3
myCar.stop = function(){
 console.log("stop");
}
Do you see a problem with this... yes, only myCar can be stopped now, not the rest of the cars coming out of the factory. Lets see if this assumption is true.
1
2
var yourCar = new Car(5);
yourCar.stop();// TypeError: Object [object Object] has no method 'stop'
So, we need this method on all cars that come out of the factory. If the stop() method were defined as part of the Car function definition in the first code snippet, then all new cars would "inherit" this, but how do we install a "stop" method now. The answer lies in the prototype property available on functions:
console.log(Car.prototype);// Object {}
The prototype property is available on all functions, but make sense only for functions that are used as constructors. The reason will be obvious when you understand their role.
The prototype property on functions point to an object which serves as the the blueprint of the objects created using that function. The newly created objects have a secret link to this blueprint.
But why is it empty in the example .. shouldnt we be seeing a drive() method on it ?
No, because we did not leverage this  prototype property to add the method to this blueprint. Look back at the first code snippet, the drive() method is defined like so:
this.drive  = function(){..
This results in every car instance getting its own copy of the drive() method. (Obviously this is not very efficient. We will correct this later.)
To understand how the prototype property works, lets add stopping functionality to the Car.
1
2
3
4
Car.prototype.stop = function(){
  console.log("stop");
}
yourCar.stop(); // stop
Note that unlike the drive() method, we added the stop() method to the prototype property. This has the effect that all instances get this method including the ones that were created before this method was added
So, that worked.  
Lets paint a picture to remember this better


If we were to redo the Car function from scratch, this is how it would look:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var Car = function(numGears){
 // per-instance properties
 this.numGears = numGears;
};

// shared code on prototype
Car.prototype.drive= function(){
  console.log("driving");
}
Car.prototype.stop = function(){
  console.log("stop");
}

var myCar = new Car(3)
myCar.drive(); // driving
myCar.stop(); // stop
This is quite strange-looking, very unlike a Java class.  But it is the way you are expected to do class-based programming in this language.
In another post, I will explore how code is shared by inheritance using the class style paradigm

[1] In the next version of the language i.e. in ES2015 / ES6, you can create classes using the class keyword. Here is a link where you you learn more about it:
Classes in JavaScript - My understanding is that it is mostly syntactic sugar that transforms into the above code.
[2] I originally intended to write about the Dojo declare feature, hence the url of this page name reads as "dojo-declare". The declare module in Dojo is used for creating Java-style classes. The widget framework  - Dijit uses this heavily.

Tuesday, March 4, 2014

Dijit Button: Accessibility

Where does a dijit/form/Button get its accessibility features from ?
By accessibily ( hereafter referred to as a11y), I mean you can press the button using the mouse, touch or keyboard( Space and Enter ) keys.
Link to demo code: http://dojo-sandbox.net/public/8225a/1
The answer is quite simple really. 

Open up the Button's template file:
https://github.com/dojo/dijit/blob/master/form/templates/Button.html
Notice the dojo-attach-events:
data-dojo-attach-event="ondijitclick:__onClick"
This "event" - ondijitclick magically gives this behaviour to the node on which its present. But as you can safely assume, 'ondijitclick' is not a native event. 

So, what is ondijitclick ?
To understand this, we need to revisit some of the basics.
The _TemplatedMixin processes the HTML template, for attach-points and attach-events, among other things. Well, this is half the truth. This part of the work is done by its base-class the _AttachMixin's _processTemplateNode method. This methods internally uses the _attach method. This is the interesting bit:
This method looks for the phrase "dijitclick" after parsing out the "on" 
If it finds one, it pulls in the allyclick module via a require
And in the final step, it attaches an event handler using on.
i.e, in case of the button, it fires the internal _onClick whenever a button is clicked/touched/keyboard pressed via- Space/Enter. So the declarative code in the Button  -"ondijitclick" basically converts to
on(node, "a11yclick", _onClick);
This helped me understand that the above line of code was another option instead of using "ondijitclick" in my template file.
I hope that helped demystify some of Dojo's magic.

In a future post I want to explore the internals of the a11yclick module

Saturday, February 22, 2014

Unravelling the Dojo Widget(Dijit)

The Widget framework in Dojo solves 2 problems and both of them, elegantly.

For a UI application developer, widgets are essential. Before I continue, It would be useful to define what a widget's purpose is, to better understand its usefulness. A UI application will consist of well-defined visual controls that a user interacts with, to view/input information. For example: Dropdown lists, Text-fields, Buttons etc. It would be extremely beneficial if these were readily available rather than having to build something application-specific. Dojo addresses this problem with its rich set of widgets - Dijit Theme-tester link.
[I wont get into a lengthy discussion of why the native HTML controls are just not enough or compare Dojo's widgets with an other framework.. Did I hear someone say jQuery UI or ExtJS :) ]

Second, and the one which I think has been solved by Dojo really well is the Widget authoring framework. It is the same architecture that's used to build the widget set seen earlier. Developing new widgets\Customizing existing widgets is a streamlined software engineering process because of this architecture. 
From here, we will dive into the internal workings of this system. It is not going to be a 101 course in building Dojo widgets. It assumes that the reader if familiar with developing widgets.There are excellent articles for those:
Understanding _WidgetBase - Tutorial
Writing your own widget - Reference Guide
dijit._WidgetBase - Reference Guide
Creating Template-based Widgets - Tutorial

By the end of this post, I hope to have explained some of the magic hidden in these framework classes: _WidgetBase and _TemplatedMixin will be the focus of this deep-dive. 
Every Dojo widget that is readily available or any new widget that you would develop would utlimately subclass _WidgetBase. This is the basic contract of building a Dojo Widget - a Dijit. Hereafter, when I use the term widget, it means that I am referring to a Dojo widget.
The _TemplatedMixin allows widget developers to specify the UI of the widget in a seperate file which will be processed during the widget construction.
Github links to these classes:
Here is a dojo-sandbox link to a very minimal widget built using these classes:
http://jsfiddle.net/deepakanand/hxxx220q/
We will copy-paste a code snippet from that link for the purposes of our discussion here:

1
2
3
4
5
6
7
8
  var MyWidget = declare([_WidgetBase, _TemplatedMixin], {
    baseClass: "myWidgetBaseClass",
    templateString: "<div></div>"
  });

  var widgetInstance = new MyWidget({}, "widgetcontainer");
  
  widgetInstance.startup();

MyWidget is the new widget which has its own baseClass and a simple template which consists of a single div element and no attach-points or attach-events.

widgetInstance is an instance of the MyWidget class.
The startup() method is the last of the lifecycle methods that needs be explicitly called(but oft forgotten) after instantiating a widget and placing it in the page.

A class diagram showing the architecture:





TODO:  Detailed description of code-path

Sunday, February 16, 2014

My experience with Dojo

I have been working on UI for a few years now. About 1.5 years ago, I started developing JavaScript using the Dojo framework. I wish I had been warned before I started, that its not yet another JS framework. It is/has eveything that an organization needs to build single page applications.
I felt it important to write about my experience with JS and all of the jQuery goodness before Dojo.
JavaScript is a still a new language despite the countless blogs and tutorials to help understand its good, great and not so-great parts. As a web developer who worked on different web-sites at school I naturally picked up jQuery. With it's expressiveness(chaining etc) and cross-browser support, it was easy to get addicted to it. The introduction of the jQuery UI framework was everything a web dev could ever ask for. Both(jQuery Core and jQuery UI) these frameworks together helped reduced tons of boiler-plate, provided great APIs and a rich widget set. Note that I never mentioned code organization so far. I still used to modularize my JS into functions and some name spacing. I would split code into short script files and include all of these on my page. Code organization was a problem I pretended did not exist. 

With the influx of all the jQuery plugins, I jumped head-first noodling with them and eventually using them in my projects without understanding that some of them do not have full-time support or are not maintained by their owners reliably. 

It was then that I realized that it takes a much more disciplined approach to build large web applications.

Forward to today, it has been a rich learning experience developing JS code using the Dojo framework. The require, define and declare functions, underpin the code organization. I learn of different ways every day to utilize one of dojo/_base super useful modules. It's refreshing to see the toolkit's approach to providing enhanced functionality but deferring to the browser default if native support is available, without polluting the global objects. The widget system known as Dijit, is fantastic. It not only has a rich set of widgets, but has a set of rules governing how widgets must be built. It's supports template-based widgets which is so much easier to maintain than widgets coded completely in JS. 
I look foward to sharing more of my dojo experiences as code samples in future posts.

Friday, July 16, 2010

jQuery Plugin for a navigation menu

There are probably a million other ways to make yourself a navigation menu. This is my $0.02. Importantly, thanks to the Open source community, John Resig, the JQuery team and the JQuery UI team.
Now, I do not know if there was a need to use javascript to create a navigation menu. It can be done with CSS, I know, but JQuery UI is all about using JQuery to manipulate CSS. So, I gave it a shot. Besides JQuery is plain fun !

Motivation: I wanted to achieve the tabbed view like the one in JQuery UI tabs across multiple web pages for a web-site that I was working on.
Solution:
The core JQuery and Jquery UI and JQuery UI CSS files. They can be downloaded from the JQuery UI site.
The navbar (thats the name I gave it!) plugin file can be downloaded from here.
Required Skills: Intermediate JQuery, HTML, CSSUsage
HTML:

<div id="navbar-container">
<ul id ="navbar">
<li id="page1_link"><a href="mockup_1.jsp">Home</a></li>
<li id="page2_link"><a href="mockup_2.jsp">About</a></li>
<li id="page3_link"><a href="mockup_3.jsp">Contact</a></li>
<li id="page4_link"><a href="mockup_4.jsp">More</a></li>
</ul>
</div> 

JQuery/JavaScript:

$("#navbar-container").navbar("navbar,page1_link,page2_link,page3_link,page4_link, 1");

You will need to add the above jquery/javascript to every page. All the arguments in the call remain the same except the last one, the number. This number indicates the item (li element) on the navigation bar that should be selected. Here,
<li id="page1_link"><a href="mockup_1.jsp">Home</a></li>
will be selected. It should look like this:







  




(I have used the new JQuery UI buttons for the sidebar. More about that later.)
So, for an other webpage, you will need to call navbar() with an appropriate number as its last argument.
i.e. if it is about.jsp, the call will be $("#navbar-container").navbar("navbar,page1_link,page2_link,page3_link,page4_link, 2");

Hope this was useful.
Useful Resources: