Saturday, April 24, 2010

Dojo widgets and their domNode

Today, I understood better with dojo widget which is so called dijit system. I realized more about what a dojo widget deeply is and how they are formed. Here I want to share my experience with every reader.

First, I want to talk about the difference between dijit.byId() and dojo.byId() which will be heavily used by any dojo user. To summarize, dijit.byId() returns a dijit (dojo widget) and dojo.byId() returns a dom node. A dojo widget maybe formed by many dom nodes, and within dojo toolkit, a widget is also a javascript object. To better explain this, lets look at a dijit.form.TextBox created below:



< div id="iBox" dojoType="dijit.form.TextBox">< /div>


What will be the output be if we simply just do dijit.byId("iBox")? It will output "[Widget dijit.form.TextBox, iBox]. it means what dijit.byId("iBox") returns is a widget object. It is very clear and simple to someone who has already had experiences with dojo; as you see there, because we created a widget in the markup, we are supposed to get a widget returned from dijit.byId().

what about dojo.byId("iBox")? what will it return? It returns a dom node object with value [Object HTMLInputElement]! Wait a second here! As what I described above -- dojo.byId() returns the dom node, should it return [Object HTMLDivElement] then? No, absolutely not. The reason is that when dojo parse the widget, it will replace the markup you created with something else pre-defined in the templates. For the dijit.form.TextBox widget, please go to your dojo directory, open folder "dijit", then open folder "form" under "dijit", then open the "TextBox.html" file within the "templates" folder under "form" folder. What you see in the html template file is how the TextBox widget is rendered. As you would expect, it is rendered by "input" tag. Thats just why dojo.byId("iBox") returns an "input" element. The same output will be obtained if you do dijit.byId("iBox").domNode. However, it is not always true!!!!

if dojo.byId() is used on a dijit, it will output the most effective tag wrapped to this dijit; whereas dijit.byId().domNode will returned the outermost tag wrapped to the dijit. For example:

< div id="iButton" dojotype="dijit.form.Button">< /div>

This is a dijit.form.Button widget, again looking down to its template, you will see a "button" tag is wrapped by 3 "span" tags outside of it. In this case, the outermost "span" tag is the outermost html tag wrapped to this widget, whereas the "button" tag is the most effective tag of this widget. As you would expect, dojo.byId("iButton") will output "[Object HTMLButtonElement]" whereas dijit.byId("iButton").domNode will output "[Object HTMLSpanElement]".

Here comes another question, where did the "id" attribute get assigned to? The answer is the most effective dom node. It turns out that dojo.byId("iButton").id will actually return the id "iButton" (even if it is considered a bad way in practice), whereas dijit.byId("iButton").domNode.id will return nothing -- "undefined" (it is an even worse example in practice).

Sunday, March 21, 2010

Object Oriented JavaScript Part2 -- "this"

People experienced with some Object Oriented Programming language like Java and Python must be very familiar with using "this" pointer. JavaScript also involves a lot of uses with the "this" pointer.

The first question that we usually need to solve is that "Where does the 'this' pointer exist?". This is a rather simple question with JavaScript. The "this" pointer exists within any "Function" object ( As some of people already know that "function" is an instance of the global "Object" object in JavaScript; therefore, we will usually say the "Function" object. ). Code below will exhibit how a function is declared in JavaScript:


function myFunction(arg1) {
console.log(arg1);
}

These lines of code simply declares a Function object and one can simply just add a line like this this.name = "myName"; within this function. As we can see, "this" pointer exists within the function definition


I guess the most confusing part is to figure out what the "this" pointer points to? A rule of thumb to define what the "this" points to is that " 'this' pointer points to the object that contains the function where the 'this' exists within ". Within the code above 'this' pointer points to the 'window' object if that function is declared in the web page globally

Friday, March 19, 2010

Stack And Heap

I believe that there are lots of developers who do not have a computer science degree and did not go from the basic understanding of computers to programming languages like me. I am neither a computer scientist nor a software engineer. Developing web application is totally just my hobby and I self-taught everything except the basic function-based c++ programming style.

I didn't understand the computer memory completely; therefore, when dealing with deep memory allocation problem, i used to just do it based on my feeling to it. A lot of Java developers think that they do not have to deal with memory allocation because of the fantastic garbage collector feature. However, better understanding the garbage collector would help yourself with dipping into the language even more. Some languages that must have a host like Javascript also need the developers to understand memory allocation if you ever consider that speeding up your code is very essential.

Computer memory used for programming is usually divided into 3 parts. Code container (what I call), Stack and Heap. Code container contains the code that your compiler compiles your programming code to. When you program a project, the code is usually in English. However, when the code went through the compiler, it will become machine code.

Stack area in the memory is the place where variables with static size are stored in. Stack follows the Last In First Out rule(LIFO), meaning that the last memory created in the Stack will be removed the first. Usually, those variables are primitive values like int, double, float and so on. (However, when you use primitive wrapper type like in Javascript, you can do "var myVar = new Boolean(true);", this variable will be considered as a reference or pointer pointing to the actual Boolean object which exists in the heap). Because primitive values usually have a static size, they are placed in the Stack area.

Heap area in the memory is the place where variables with dynamic size are stored in. The reason why we call that dynamic size is that size of values in the Heap is allowed to be determined at run time. Usually, with Object Oriented Languages, actual objects are stored in the Heap and object pointers are stored in the Stack. Therefore, when you create two pointers and copy the one pointer to the other one like "obj1* p1 = new Obj(); obj1* p2 = p1" in C++, you are just copying the pointer from p1 to p2 and changes made to the object "p1" points to will directly affect the object that "p2" points to because they are actually pointing to the same object on the Heap.

I love cars just as much as loving web development. The garbage collection feature is good and convenient but just like comparing automatic and manual transmission on the cars, automatic is a convenient feature but it is never as fast as driving the manual one. The garbage collection feature is convenient but it has to search for memory that will not be used then remove it, it makes the process a bit slower.

Tuesday, February 2, 2010

Object Oriented JavaScript (Basic)

Hi all, few days ago, I picked up a book called "Dojo: The Definitive Guide" and realized that this book isn't really good for javascript beginners or those who have experienced only event-based javascript. Not only does using Dojo require understanding deeply on JavaScript, but also other JavaScript toolkits. To dive into Javascript programming from a beginner to a deeper js programmer, a few keys that need to be understood. Javascript closures, anonymous functions and objects. (These are not required for people who want to learn JavaScript and design a website, but without these skills, the websites you design or develop do not belong to the modern world)



The way I learnt these was actually by reading books. The main book I used is called "Object-Oriented JavaScript" by Stoyan Stefanov. This is actually the only book I completed reading without jumping into web resources. Other books are also good on this topic such as "Pro JavaScript Design Patterns" by Ross Harmes and Dustin Diaz. I didn't use this book much since I have known OO design patterns from my java and c++ experiences.



Before going to the three topics mentioned above, there are still something you need to know about javascript. Javascript is a dynamic language, therefore, it does not have static types; which means you can assign any value to a variable without declaring its type.

var str = "this is a string"; will assign the whole string into the variable without having to declare a 'String' type like what you did in Java or C++. As I said, you can assign anything to a variable, even a function; therefore, passing a function into the parameter list in a function is totally valid in JavaScript. JavaScript doesn't have curly bracket scope, but it has function scope (want more info? refer to the books I mentioned above). Also, in JavaScript, Arrays, Functions and custom defined objects are all objects and JavaScript Objects are passed by reference (Refer to the books I mentioned above for more and clearer info).



Closures:



It is a very powerful feature in JavaScript and it is important for a JavaScript beginners because without understanding of js closures, the behaviours from your code maybe different from what you expected. I will give some simple explanations about this term here. Let's take a look at the code below:




function myFunc(){

var myVar = 5;

var myF = function(){ console.log(myVar); };
return myF;

}

var f = myFunc();

f();

//what will the line above output on the firebug console?

You can test this code in the firebug console. The output is '5'. The point of this is when a function returns another local function to a variable outside the function itself. This variable holds the reference to the returned function. As I mentioned above, JavaScript has function scope. Supposedly, variables defined in a function are not accessible by variables or functions defined outside the function; but closures break this rule.



Anonymous Functions


This is easy, and it was already seen from the example above, but I will still explain a little here:




// The regular way to create a function
function myFunc(){

// behaviors

}





// Use anonymous function

// then assign the anonymous function to a variable

var myFunc = function(){ // behaviors here };




Objects


Object Oriented JavaScript is different from other Object Oriented Programming language like java and c++. JavaScript does not allow you to create classes. While other OO languages use class to define objects, JavaScript uses objects only. There are two ways of creating a JavaScript object:



//Object Literal Notation:
var myObj = {
member: 5,
method: function(){}
}

//Constructor function
function myObjFunc() {
this.member = 5;
this.method = function(){};
}
var myObj = new myObjFunc();


Prototype is another feature of object oriented Javascript. Each function has a prototype. Prototype acts like an object. In each object created by using constructor function, there is a pointer linker pointing to the prototype of the constructor which created the object. By using prototype, we could establish the inheritance feature of Object Oriented JavaScript.

Monday, January 25, 2010

GWT vs Searchability (Search Engine Optimization - SEO)

GWT has been a great tool to learn since I started. However, at the same time, I realized couple things that are not supported by GWT.




  • Multiple HTML pages linkage

  • Although it is possible to have more html pages whey you deploy, but then the history support thing will not work with those individual html pages anymore.

  • Lack of Searchability

  • Unless you create content in the hosted html file, there is no way your website will be searchable by search engines like google because they read html content. It is a common problems for ajax applications, but the usage of
    GWT is limited to only RIA(rich internet applications). Go on this link, they also talked about it.


    Possible Solutions:

    To integrate with Search Engine Optimization (SEO) on GWT, Jeff Dwyer's book Pro web 2.0 application development with GWT may give you some hints. Search Engine Optimization is on page 333 in chapter 12. Jeff talked about SEO specifically according to the example "ToCollege.net" through the book but readers should use possible solutions with more considerations based on the purpose of your web application. The Three possible solutions he talked about in the chapter were great choices, and the first option was what I came up with as well last night when I was struggling about what to do about. However, my application is a 'blog', therefore, I thought creating individual pages for each blog entry may work better.

    Ajax is a very cool web tech but as if you want your web site to be searchable, you will have to stick with html-based content at least for now. GWT will still be a very good tool to use if you are developing a browser-based application. However, do remember to always clear yourself with the purpose of your web project: is it a content based website? or is it a RIA?

    Friday, January 22, 2010

    Open a (web) business in China

    I have to claim that all the content belong to my personal opinion; I do not represent anyone and this post does not represent any group or individual's opinion!



    It is well known that China has the biggest population ratio in the world and obviously along the development, China also has the most public internet users. This element attracted many big worldwide web companies so that they all want to take some market share from this huge internet market. However, not many worldwide web companies have earned the success they expected. Reason ???? Cultural Differences!



    I was born in China and raised in China until my college time came into play. I have gone back to China for visiting almost every year since I came to Canada. During the many years I have been in China, I have traveled lots of places. Since elementary school, I have been sent to private schools away from my parents. I even attended my high school in Beijing. Therefore, I believed that the experiences I gained from China is enough for me to point out at least something (Of course I am not able to talk about all). In addition, I have been studying and working overseas for almost 5 years now and I have known and have been good friends with many people who are from different countries worldwide.



    The Society & The Population


    The biggest problem I think that causes lots of companies to have no clue what to do about the Chinese big market is that they do not understand China enough. My classmates and even some of my good friends all think communist countries like China share everything with each other equivalently. OMG, I found it was stupid! How do people think like that? It was such a naive thought. "China is a communist country which has special characteristics of China" this is how the society of China is summarized. Why is it still a communist country if people do not share everything they have? Because the nature of human already disagreed with it. Everyone is selfish, although some of people are not as selfish as others, although the level of selfishness of some people are very low, we are still selfish. China can not achieve perfectly communist because of its population, its history and many many more reasons that I personally can not come up with. Think in this way, if there were only 2 people, you and your best friend; if you are not very rich and your best friend is not very poor, you can probably share everything you have with your best friend. Can this still happen if any of the conditions stated above is changed?



    The Power & The Population


    Some people in China are very unhappy with the Communist Party in China. It is nothing weird or unusual. Because Communist Party is the only party holds the power in China, there must be people unhappy and happy with it. Since elementary school, we have had a class leader from the students in each class. Wait a minute, it maybe another difference between China and Western Countries like US and Canada. We have had a class leader since elementary school, who helps the teachers manage the class. Why can't a teach himself or herself manage the class? Reason 1, we have too many students in each class, my elementary school had 37 students in each class (well, it was the first private school in my hometown, not many people could afford at that time), other public elementary schools probably had 60-70 students in each class. My Junior highschool class had 68 students.... Reason 2, the leadership needs to be educated to students, but reason 1 truly is the main reason. Of course some students are unhappy with how the leader manages but if the leader can stand at his position, it means the people who are happy with him are more than the people who are not. Usually what happens is that this leader will lead the class for the entire 6 years at the elementary school. Will the changing of the leader improve the overall performance of the class or make a lot of differences? Most likely NOT! China is like a big class. If the power was controlled by some other unknown parties, could China have developed as fast as what it does now? Most likely NOT.


    I remember at elementary school, each grade of the school had one flag. The class which can obtain this flag indicates that it has been doing the best in the past week. How does the school determines which class gets the flag? There were checkers in each grade, and they do not check the quality of products! They check the quality of students. Those checkers also came from each class in a grade, but the checkers were not supposed to check the students from their own class. They check if students do not respect teachers and other students, if students swear, if students whisper during the class time and if students wear uniform and wear uniform correctly and so on. Generally, schools which are doing well in my hometown all operate like this. I can not summarize what it means and how it is related to knowing the Chinese culture but I believe some of you are able to come up with some thoughts about this.



    Economy and The Population


    China is well known as a country that was not very much affected by the currently bad economy. People in the US are selling their houses and cars because losing jobs caused them not to be able to afford those objects. What about in China? My parents got a new car in 2009. Popular cars in the dealers are always out of stock and people need to pay extra money to get the cars they want. To encourage people buying cars, car dealers have lowered the price of their cars in the US. This is exactly the same thing happened in China, but why there is still such a big difference? Because western people like to spend the money they will be making in the future at present, whereas Chinese people chose to save money first then spend it on something they want to buy when they have enough. It is an arguable discussion because truly, Chinese people will never enjoy as much as American or Canadian people would. However, if you look at this problem in a big picture. Because Chinese people have money to spend in the bad economy, dealers and stores will not stop selling products to consumers (they are still making money), then people who work at stores and dealers will not lose their jobs, then factories will still have to make products to feed the need from stores and dealers, then people who work at the factories will not lose their jobs either, at the end the people will still make money then start this circle again. Then think of combining how many Chinese people there are with this circle. (At here, I do not want to talk about any sensitive things such as how governments controls the economy very well. All I have talked about is what everyone can easily see.)



    The Education & The Population


    There is no need to talk about how school educate students because at the end, it is just the same thing as any other countries; plus I already talked a little bit in the "The Power & The Population" section, but let's talk about the education from parents.


    American people and Canadian people believe that Chinese people are not open enough. I certainly agree but it depends on from which way you are looking at the openness. Let me ask you this question, have you ever dated with a Chinese boy or girl? Have you ever hanged out with a Chinese person for so long that you could say that you know him or her very well? No matter what your answer is, we all certainly agree that the education from parents is very very important, but I could certainly say that the education from the parents in China is more important than the education from school. My dad always tells me "If you wanna be successful on your career, you have to know how to become a good person". There are some differences about this topic between China and US/Canada.


    For example, it is clear that eventually when kids grow big, they will all have girlfriends and boyfriends, and they will all know everything about sex. However, none of the Parents would want their kids to think about this too early because it maybe a bad influence to their studying and living, even in the US and Canada. However, maybe American and Canadian parents think they do not have to be too worried about this as long as they tell their kids "not to"! It is different in China; Chinese parents can not only tell their kids "not to" because of the population. When the population raises, the bad influence gets worse. Let's think in this way: if there were only two people and one person believes in something and trying to convince the other person to believe in it, the second person will probably believe in it or probably not, so there is an equal possibility of being influenced or not; but if there were four people and two of them believe in something and two of them don't, and if the first two people try to convince one person from other two then the other, the possibility of the second two people being influenced got much higher. You will probably say "I will never just believe something when people just tell me to", but if you think about this to a kid. Kids are much more easily influenced. That's why Chinese parents have higher responsibility of educating their kids to not badly influence others and to not be badly influenced. In other words, Chinese kids need to be watched tightly.



    The Average Salary & The Population


    When your thinking about opening a business in China, what you are looking at is the population. You might think "China has 1.5 billion people, if every of them buys my product, I will make so much money", but usually you will always question yourself "How many of them will actually buy my product?" It is well known that usually it depends on the quality and price of the product. People usually say something like "you get what you paid for" and ideally, the quality is proportional to the price. However, the ideal case needs to be broken in China.


    Chinese consumers do not make as much money as American and Canadian consumers do. At this point, I am talking about average salary. There is surely people in China making billions of dollars a year and that amount of people is actually quite a bit if you compare with the amount of the rich people at the same level in the US or Canada; but comparing to 1.5 billion Chinese people, that amount is very very small. If you are targeting at the Chinese rich people, you can skip this section absolutely but keep in mind, if you are just targeting the rich people in China, then the 1.5 billion population doesn't really make much difference for your business anyways. To state this, the amount of Chinese people who make less than average salary is much much more than the amount who make more than the average. The key to win the business in China is to know how to make the money from the poor people.


    For instance, years ago, Microsoft was almost equivalent to a monopoly in the computer operating system market. All of the computers on the market came with Microsoft windows at that time. Their windows 95 was sold for 89 dollars in the US. It wasn't expensive at all if you think about that Microsoft had invested billions of dollars on it. To many Chinese people, that 89 dollars at that time could feed a whole family for a month. If you argue that we should not talk about that period because not many people owned a personal computer, we will talk about 2009. In 2009, the average salary in China per-person is approximately 3500 Chinese yuan, which is equal to about 500 US dollars. Windows 7 home premium on Microsoft.com is listed 199 US dollars for the Full version and 119 for the upgrade version. Would you buy a windows 7 home premium if you only make 500 dollars a month? What does it the high price cause? Answer is: cracked software and even an alternative which will cost less or nothing, like linux system. Not to surprise you, a cracked version of Window7 perfessional in China is sold for about 3 US dollars, which may have problems but price is already much more important than quality in this case. but Microsoft is very smart about that, they have been selling home basic version which only costs 399 Chinese yuan (about 60 US dollars) to encourage the Chinese market.



    I just hope that my experience will give some of you a hint when you want to open a business in China. Please forgive me if the content is not very well organized and maybe even not easily understandable. I will continue to write if I have more time

    Thursday, January 7, 2010

    GWT is the way, GWT makes sense!

    Why GWT (google web toolkits) is the way? GWT is the way of what? Why do I have to mention "it makes sense"?


    Nowadays, almost everyone in the world knows what desktop applications are because owning a computer for an individual is already not so hard as 20 years ago. Especially in developed Countries, most people carries laptop computers to work, to go to school and even for travelling. As internet becomes faster and covers more places, laptop computers seem to become a little bit overabundant and too heavy to carry everywhere; Because people already can do basic daily work via the internet, such as word documents, pictures storing, and watch videos and so on. Besides these, the powerful internet search engines provides internet users with world wide information based on their own interests. Thank to those powerful web browsers. Then Netbooks came into play with their slower but smaller processors, smaller hard drive storage, and smaller memory space than most laptops. Why is that good? Because you won't need that much storage and memory space if the only thing you will need is just a web browser most importantly.


    As Ajax based web applications get more popular, more and more previous desktop application programmer started to be interested in web applications. However, the only programming language web browsers are able to understand currently is Javascript. A single threaded, non-object oriented programming language (it does allow scripters to create "object" but it is very far away from what the real OO principles can benefit). Here the question comes in, how web applications programmers can make easily reusable and maintainable code as they could with desktop applications? How can a web application become as efficient as a desktop application to the developers? (Don't get me wrong on this question. I know most server-side programming languages are object oriented.)


    GWT is tool to allow OO principles to be applied. It allows web developers program the front end of a web app in Java. Instead of compiling Java code to Java byte code, it compiles to JavaScript. It is not only easy for programmers to apply OO principles for highly reusable and maintainable programming design, but also easy to debug.


    Let's think this way. If Object Oriented Programming has been a very valuable thing to replace Procedure Oriented programming, then it should be applied to web programming as well. So far, GWT is the tool letting you do it; therefore, GWT is the way for web programming. If people usually say 'Using Object Oriented Principle to program makes more sense than using procedure oriented', then GWT makes more sense for web programming.

    Saturday, January 2, 2010

    develop GWT application with Netbeans on Ubuntu (How To Set Up)

    As I am writing this, the recent versions of GWT, Netbeans and Ubuntu are GWT2.0, Netbeans6.8 and Ubuntu 9.10


    I have been using Ubuntu linux for 6 months as I am writing this, so far I love it especially the 9.10 release. Below is the image that I just took when working on dual monitors with Netbeans6.8 open on the right side. As you can see, the fancy theme + bottom panel + linux system really make ubuntu the best operating system to my tast.



    Netbeans is an IDE which was originally built for java development; because of the great work of the developers from Sun Microsystem, Netbeans has been compatible for many kinds of development such as python, ruby, php and c++ and so on. Do not doubt about its portability, because it is written in Java. Some other IDEs are also great choices eg. Eclipse, but since I have been using Netbeans for a while on windows systems, I would like to stick with something that I am used to.


    GWT stands for google web toolkits. It is a web development toolkits written in Java by google. It complies java source code to javaScript and HTML. It makes web application development much easier for developers who are used to desktop applications. I will skip the details how GWT works and leave it for you to find out at code.google.com/webtoolkit/


    First thing you will do is to download Netbeans, GWT SDK and GWT4NB(GWT plugin for Netbeans users).

    • Netbeans can be downloaded at http://netbeans.org/ (choose the java version)
    • GWT SDK can be found at code.google.com/webtoolkit/download.html
    • and the GWT plugin for Netbeans users can be downloaded at this link (choose the right version to use, at the time I am writing this post, the correct version to use was 2.6.16).


    Install Java SDK (if not already installed, there are instructions everywhere on the internet, or can follow ubuntu help at this link),Netbeans, GWT SDK and GWT4NB.

    • Netbeans installation instruction can be found at your netbeans download page, it is easy to follow.
    • GWT SDK installation can be found at the GetStarted section on google's gwt web page.

    Next you will do is to add GWT4NB to Netbeans:

    • Open Netbeans
    • select "Tools"(on the top tool bar) --> "Plugins";
    • at the currently opened window, select the "Downloaded" tab,
    • click on "Add Plugins", find the place where you downloaded GWT4NB to then "open" it
    • click on "Install" at the window,
    now you are done with it.


    How to configure servers or anything that you need for working with Netbeans can be found on the internet. You can work with GWT's development mode when your application is under development. It is easier for debugging procedures