domingo, 4 de agosto de 2013

The Javascript Global Object JavaScript mystery

Today I will talk about a mystery that should be more noticeable because it is on the root of the code execution but only seems to be visible when having to face with different javascript runtime implementations (not only the browser). Since most javascript only face with The single environment the browser, lets talk about it: the problem of The javascript globals objects:

What is THE Javascript Global Object? Take in consideration the following  code:
var a = 1;
b=2; 
Here we declare 2 variables , but what's the difference. Well, in terms of usability the difference is that b is declared as a property of the global Object 'window' (in the browser) and so any javascript code can access this name (unless explicitly overriden).

So here is the first javascript mistery, So, how can I know, (as a javascript programmer), what is this Global Context Object ? For example, I need this object for performing some global evaluation and for that I need this Global Context object. The answer is simple:

`this` outside any function will be the global object.

...
Explained in other words, this is my way of understanding The Javascript Global Object:

Every code must be runned inside a function, even that code for which we don't see its corresponding function, like when we use eval() or the top-most code that is not inside any function. All the other javascript code resides on a function body. For the top most javascript written code we 


the chat conversation in irc.freenode.org#javascript that teach me :

(Cancerbero_sgx): hi all. question: when I assign a value to a name without the 'var' keyword, like global1=1, those variables are stored as properties of some global object, for example, in a browser on the 'window' object. Does that depends on the implementation?, or has the javascript language some reference this object ? example: for(var v in StandarGlobalObject){...} ? thanks in advance

....


(dwcook): Cancerbero_sgx, it's a property of the environment, not the implementation, whether the global object is the value of some global variable. In browsers, it is `window`.

(dwcook): There are other ways to access the global object. `this` outside any function will be the global object.
aha! thanks!


(Cancerbero_sgx) dwcook: so the implementation sets this initial environment value. Your "other ways to access" was what I wanted to know, thanks!

(dwcook): Cancerbero_sgx, no, it's not implementation-dependent. In different environments that all use V8, it could be `window` or `global` or something else.
However, the other way I mentioned is not dependent on implementation or environment.


(dwcook)It also works regardless of whether you're using strict mode.


(Cancerbero_sgx)aha nice to know, again thank you very much, these are the misteries of javascript that are hard to find googling ;)

(twey): Cancerbero_sgx: The global object is an object you specify when you're creating your Javascript environment (e.g. using V8).  It's up to you whether you give it a name; in browsers it's standard to call it ‘window’, but the only way to access it for sure no matter where your script is running is to use the global ‘this’.

(twey):  Cancerbero_sgx: A top-level name is just a reference, similar to (function() { var v = { }; v.v = v; return v; })()

(Cancerbero_sgx) twey: aja but for me that come from an OO language , it would never occur to me to reference 'this' in the global-root scope. till this moment 'this' only maked sense to me  inside a function and the context applyed to the function call. thanks!

(twey) Yes, the global ‘this’ is kind of magic.  Also, JS is also an OO language.  :þ



Well, an old javascripter that admit it is magic related to this issue. It is a mystery indeed.

But immediately we we start to suspect a relationship between the keywords var, this and with.

The first to notice is that, when declaring a named value, if we omit the keyword 'var' (when declaring a variable) or if we omit the keyword 'this' when declaring an attribute then the name is assigned as a property to the global object, in the case of browsers the window.  The following code try to show what i'm talking about:
<script>
// the Global Object. Because we are in the top-most context (no function sourrounding us) even if we are declared with 'var' we are global variables (properties of the current global object 'window'). This is an special case!
var GLOBALOBJECT=this; 
var Class1 = function(){
    this.attribute1="hello";
    nonattribute1="world"; //missing 'this' so this is a global veriable, this is a property of GLOBALOBJECT    
    var DeeperContext = function() {    
     var var1="just a veriable"; 
     global2="missing var so i'm global"; 
     this.attribute2="instance attribute";
     nonattribute2="missing this so i'm global"; // notice that DeeperContext constructor is executed on a second level context, but nonattribute2 name is assigned to the GLOBALOBJECT, not the parent context as some may expect.  
    }
    this.attribute12 = new DeeperContext(); 
}
var c1 = new Class1(); 
console.log(GLOBALOBJECT); //at this point the GLOBALOBJECT contains 2 new properties nonattribute1 and nonattribute2
</script>

About me

this is, Sebastián Gurin - cancerberoSgx - as a software developer


These are some notes about the author of this blog with some links to his work, mostly related to my free software projects.

 

Developer profile

I have several open source software projects in many sites, but mostly in code.google.com and github.com. These are the links to my profile on each of them: 

 

How all this started? 

When I first saw a computer I always wanted to "solve its secrets" so I can use it for my own purposes. Have the luck of love programming, since the very beginning, and at that time (the 90's) the Internet wasn't what it is today.... TODO

What I like the most

TODO

My projects

TODO

miércoles, 29 de mayo de 2013

Get final HTML markup of a JavaScript application using rhino - envjs

This article briefly describes how to dump the final HTML markup of any web site using serverside tool rhino-envjs. We will work into the release root folder so "cd" to it.

step 1 - download latest envjs release (as this writing 1.2) and uncompress it.
step 2 - download ant and run "ant" on the previously uncompressed envjs folder. This should build envjs. step 3 - create the file test1.js with the following content: 
load('dist/env.rhino.js');
var url = "http://jquery.com"; 
window.location = url; 
print(document.innerHTML+"");
step 4 - in a shell enter the following command:
java -cp rhino/js.jar org.mozilla.javascript.tools.shell.Main \
  -opt -1 test1.js > test1.html

If everything was fine you can open the generated file test1.html with firefox and see the jquery generated markup, not a very visual replica but often useful for SEO and those. For each JavaScript error a Java exception will be printed on stderr.

In my case this is useful for 100% JavaScript web applications SEO support.

domingo, 17 de marzo de 2013

Make a single .jar from many

What if  some project require several Java .jar files and for some reason you want to work with a single .jar with all of them inside? Or what if want to distribute your library, that requires several .jar to work, in a single .jar so it is less painful to new users? If you have permission on the other jars this is not a problem at all. The following is a sh script that uses the unzip tool:


rm -rf jartmp
mkdir jartmp
cd jartmp
unzip -u ../path/to/someJarA.jar
unzip -u ../path/toother.jar
unzip -u ../ahother/one.jar
zip -r myLibrary-alldeps.jar *
cd ..
rm -rf jartmp

The previous script will generate a myLibrary-alldeps.jar that contains the three previousgiven .jars files, all inside. This way the user of your library do not have to download your library's dependencies. Hope this serves somebody.

martes, 4 de diciembre de 2012

Guidelines for writing GWT Overlay types

Guidelines for writing GWT Overlay types

This post is related with an older post Eclipse templates for overlay types about the same topic. You can find eclipse java code templates for code proposed here in that section. Now, that I have my ideas more clear and tested this is a summary.

When writing overlay types we have to take in consideration two main ideas:

  • we are writing a Java class that will be used by Java users
  • we are overlaying a JavaScript object with an API designed to be used in JavaScript

The following presents some guidelines learned and adopted in my GWT libraries porting javascript libraries like YUI and raphaël to GWT using 100% overlay types for a zero overhead Java API implementation.

Constructor

Use a static method with a simple name like create() or newInstance() that return an empty object or an object with some desired initialization state. Example:

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
}

Properties

In Java we use the Bean convention for accessing obejct attributes / properties with getters and setters methods:

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
 public native final String getColor()/*-{
  return this.color; 
 }-*/;
 public native final void setColor(String color)/*-{
  this.color=color; 
 }-*/;
}
End User example code:
MyOverlay o = MyOverlay.create(); 
o.setColor("red"); 
aController.method1(o);

Nevertheless, we must remember that "we are overlaying a JavaScript object with an API designed to be used in JavaScript". In JavaScript we normally are able to define an entire object in a single statement. For accomplish this in Java we need our setters methods to return the this object so we can perform method chaning. Also, but not so important, se omit the prefixes get/set for there methods

public class MyOverlay extends JavaScriptObject {
 protected MyOverlay(){}
 public static native final create()/*-{
  return {}; 
 }-*/;
 public native final String color()/*-{
  return this["color"]; 
 }-*/;
 public native final MyOverlay color(String color)/*-{
  this["color"]=color; 
  return this; 
 }-*/;
}

End User example code:

aController.method1(MyOverlay.create().color("red")); 

Much more similar to its JavaScript common counterpart aController.method1({color: "red"}), don't you think ?

Some notes:

  • We use setters and getters without the prefixes "get" or "set", so our method names are the same as the property name. This make it easy to use IDE tools like eclipse Java Code templates for generating the getter/setter code automatically.
  • In JSNI code we use string literals this["color"] instead variable names like this.color so the closure compiler (available optionally in GWT > 2.5) don't mess up JavaScript Object property names.

For those Java convention lovers I think it wouldnt cost too much to have "normal" java bean getters and setters AND this kind of shorter accessor methods for those who like to define object more "a la" javascript.

About Performance

Unfortunately the proposed code style here adds some overhead to the JavaScript code output produced by the GWT compiler. In the following example, I have created 2 JSOs, one called NormalBean that follows the Java Bean getter/setter conventions and other one called JsFriendlyBean that uses the solution proposed here with setters that return 'this' for method chaining. Then I use them both and compared the resulting JavaScript output code by GWT compiler using -style PRETTY and -optimize 9 compiler options. This is the result:

Java Sources:

NormalBean normalBean = NormalBean.create();
normalBean.setColor("turttlered1");
normalBean.setAge(13);

JsFriendlyBeam jsFriendlyBeam = JsFriendlyBeam.create()
 .color("turttlered2").age(14); 

Window.alert(normalBean + " - " + jsFriendlyBeam);

JavaScript output:

normalBean = {};
normalBean['color'] = 'turttlered1';
normalBean['age'] = 13;
jsFriendlyBeam = $age($color({}, 'turttlered2'), 14);
$wnd.alert(normalBean + ' - ' + jsFriendlyBeam);
...
function $color(this$static, val){
  this$static['color'] = val;
  return this$static;
}
function $age(this$static, val){
  this$static['age'] = val;
  return this$static;
}

As you can see, the setters of the NormalBean are inlined in JavaScript with zero-overhead while the setters of JsFriendlyBean are not. In the later, JavaScript functions $age() and $color() are created and called and that adds little but some overhead.

I cannot find a workaround for this. Tried with single JSNI statements like the followings but the result is the same:

public native final JsFriendlyBeam age(int val) /*-{
 return (this["age"]=val, this); 
}-*/;
and
public native final JsFriendlyBeam age(int val) /*-{
 return (this["age"] = val || true) ? this : null;
}-*/;

If anybody has an idea about how this setters can be written so they are inlined in JavaScritp output, pleas share it with me :)

martes, 27 de noviembre de 2012

HTML to valid XML code using tidy.

Sometimes you copy HTML source code from a web page that is not valid. Some tools, like mine htmlminimizator requires valid XML fragments to work. In this case we need to transform HTML sources to valid XML. I'm doing it fine with the tidy utility like this.

First I suppose you have your HTML code fragment in a file called test1.html, then I perform :

tidy -asxml -ashtml -utf8 test1.html 

Hope that can be of help to others in a similar situation.

miércoles, 31 de octubre de 2012

Using YUI in GWT UIBinder

About this document 

This document try to document a new feature of the toolkit YUIGWT for using YUI markup in GWT UIBinder.  It will no try to teach you how to use neither YUI or YUIGWT or GWT UIBinder (the user is supposed to know the basics of these technologies).

Online tests


YUIGWT example gallery contains the first tests related to using YUIGWT and UIBinder. The examples are:
  • uibinder test 1 - contains some yui widgets and GWT widgets mixed - layouting using YUI cssgrids.
  • just one, making more for the 1001 usescase... stay in touch....

Introduction

In GWT applications it is common to use UIBinder to separate the markup and style (design) from Java code (behavior).

And YUI proposes a very similar thing. All YUI widgets can be created from a markup structure. This markup structure is defined by each YUI widget. Some simple widgets like Y.Button only requires you to give a <button> element, but other more complicated YUI widgets like tabview, treeview, etc need you to provide a more complex markup (example).  This is somehow related to yui philosophy's of "Progressive Enhancement" @see http://yuilibrary.com/yui/docs/tutorials/gbs/

UIBinder users can mix both GWT Widgets markup and plain HTML Markup in their UI. Also the user is able to bind some of these markup elements to actual Java Objects fields in its Java code where the behavior, controller and modeling of the application is written.

In this document we will discuss how to use YUI Widgets proposed markup together with GWT UIBinder for rendering YUI components using UIBinder in a YUIGWT application.

Solution Summary

In general, the solution proposed here is the user to write YUI plain HTML markup for its YUI widgets in the UIBinder ui.xml, and mark them with an special class name for indicating the framework that that HTML element is a YUI widget and must be "post rendered". Then the user binds these widget elements in the UIBinder java's and after creating the UIBinder main Widget, ask the framework to render all the YUI elements. Later in the code, the user can ask the framework to return the appropiate YUIGWT Widget java class from a certain html element for work with the widget in Java. Hope this can be cleared in the following:

Example

In the following UIBinder example we use YUI cssgrids for layouting, create a yui tabview with some mixed YUI and GWT buttons inside:We commented each YUI element introduced in the markup:

<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
 xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:y="urn:import:org.sgx.yuigwt.ui">

<ui:style>
</ui:style>


<g:HTMLPanel>

 <!-- yui cssgrids -->
 <div class="yui3-g">
  <div class="yui3-u-5-24">
   <!-- yui button -->
   <button ui:field="yuiButton1" class="yui-button">the first YUI Button</button>

   <p>lak sjdlkaj slkdj alk sdlkaj slkdj lak sk djla sd</p>
   <p>lak sjdlkaj slkdj alk sdlkaj slkdj lak sk djla sd</p>

  </div>
  <div class="yui3-u-19-24">

   <!-- YUI tabview -->
   <div ui:field="tabView1" class="yui-tabview">
    <ul>
     <li>
      <a href="#foo">foo</a>
     </li>
     <li>
      <a href="#bar">bar</a>
     </li>
     <li>
      <a href="#baz">baz</a>
     </li>
    </ul>
    <div>
     <div id="foo">

      Some content with two buttons - one yui's and other GWT's<br />
      
      <!-- a YUI button -->
      <button ui:field="yuiButton2" class="yui-button">another yui button</button>
      
      <!-- a gwt button -->
      <g:Button ui:field="gwtButton2">..aGWTButton..</g:Button>

     </div>
     <div id="bar">
      a single GWT button:
      
      <g:Button text="GWT button1" ui:field="gwtButton1"></g:Button>
     </div>
     <div id="baz">baz content</div>
    </div>
   </div>

  </div>
 </div>

</g:HTMLPanel>
</ui:UiBinder>


Two important things to notice here:
  • For YUI Widgets we are writing using the same markup as expected and documented by YUI Widgets. For example, we give a plain html element <button> for creating a YUI Button, and give the markup documented in TabView Documentation - Minimal markup required.
  • We want to bind with GWT UIBinder the html elements corresponding to a YUI Widget, so we annotate them with ui:field="myfield".
  • Each html element corresponding to a YUI Widget must be annotated with an special class name corresponding to the aforementioned Widget. For example we annotate indicate it is a YUI Button using class="yui-button". This is how we indicate "this element must be rendered as a YUI Button"



And now the Java Sources corresponding to the UIBinder Composite definition I hope it is self documented:

package org.sgx.yuigwt.ui.test;

import org.sgx.yuigwt.ui.YUIBinder;
import org.sgx.yuigwt.ui.YUIBinderListener;
import org.sgx.yuigwt.yui.YuiContext;
import org.sgx.yuigwt.yui.event.EventCallback;
import org.sgx.yuigwt.yui.widget.button.Button;
import org.sgx.yuigwt.yui.widget.button.ButtonEvent;
import org.sgx.yuigwt.yui.widget.tabview.TabView;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

/**
 * this is a common UIBinder Composite class. Notes:
 * 
 * < p>
 * 1) for YUI, we are binding plain HTML Elements, like @UiField Element
 * tabViewEl1;
 * < /p>
 * 
 * < p>
 * 2) then in the constructor, after this GWT widget is initialized with
 * initWidget(uiBinder.createAndBindUi(this));, we call YUIBinder.bindYUI
 * passing this Element UIFields corresponding to YUI stuff and register myself
 * as a listener to be notified when YUI binding is done to start working.
 * < /p>
 * 
 * < p>
 * 3) in yuiBinded() callback we ask for YUI Widgets and start working with
 * them.
 * < /p>
 * 
 * @author sg
 * 
 */
public class YUIInUiBinderTest2 extends Composite implements YUIBinderListener {

 interface MyUiBinder extends UiBinder< Widget, YUIInUiBinderTest2> {
 }

 private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

 @UiField
 Element tabViewEl1;

 @UiField
 com.google.gwt.user.client.ui.Button gwtButton1, gwtButton2;

 @UiField
 Element yuiButtonEl1;

 @UiField
 Element yuiButtonEl2;

 private YUIBinder binderUtil;

 private Button yuiButton1;

 private TabView tabView;

 public YUIInUiBinderTest2(YuiContext y) {

  initWidget(uiBinder.createAndBindUi(this));

  binderUtil = new YUIBinder();

  /*
   * bind YUI stuff manually passing this Element UIFields corresponding
   * to YUI stuff and register myself as a listener to be notified when
   * YUI binding is done
   */

  binderUtil.bindYUI(y, this, new Element[] { tabViewEl1, yuiButtonEl1, yuiButtonEl2 }, this);

  /*
   * the gwt widgets can be used right away, but for using YUI widgets we
   * need to wait until binding is finished, see method yuiBindede() below
   */
  gwtButton2.addClickHandler(new ClickHandler() {
   @Override
   public void onClick(ClickEvent event) {
    Window.alert("gwtbutton1clicked");
    tabView.selectChild(2);
   }
  });
 }

 @Override
 public void yuiBinded() {
  /*
   * all YUI stuff is ready and rendered, we obtain the YUI widgets and
   * work directly in java:
   */
  yuiButton1 = binderUtil.getWidget(yuiButtonEl1).cast();
  tabView = binderUtil.getWidget(tabViewEl1).cast();

  yuiButton1.on("click", new EventCallback< ButtonEvent>() {
   @Override
   public void call(ButtonEvent e) {
    tabView.selectChild(1);
   }
  });
 }

}

Interesting stuff here:

  • Unlike GWT widgets, for work with YUI Widgets we will bind plain HTML Element (com.google.gwt.dom.client.Element).
  • We need to manually call our "YUIBinder", passing all the @UIField Elements correspondiing to YUI widgets and later, when the binding is dont, we can obtain the YUIGWT Widget classes to work with them in Java.

Known Issues

  • Some GWT Widgets are not designed to contain any HTML content only other GWT widets, so it is possiblt that including YUI Widgets there cannot behave well.
  • Putting a GWT Button inside a YUI TabView will make the GWT button to loose click handlers... ?

How this works and some decisions.