Archive for the ‘Crockford’ Tag

JQuery 2009 & AJAX Experience 2009   Leave a comment


John Resig
Photo By dlr2008 On FlickR.com

JQuery Conference 2009

This conference took place at the Microsoft Research Center in Cambridge Massachusetts on September 12 & 13, 2009. This was a small but intense gathering of JQuery and JQuery UI core developers and assorted developers working on extensions to JQuery (aka plug-ins). There were about 300 participants most of whom were intensely involved with JQuery. Your humble scribe was one of the least informed participants. JQuery has never looked stronger, the development team is cohesive and motivated, and community support is extensive. John Resig’s numbers indicate that something in excess of 35% of all public sites running JavaScript are using JQuery. The library wars are over. Let the framework wars begin. The conference agenda and speakers list and slides can be found by starting: here.

JQuery core is stable at release 1.3.2 but 1.3.3 is coming “real soon now.” The 1.3 versions have focused on optimization, simplification and (proactive) HTML5 support.John’s talk about recent changes to JQuery Internals can be found here. Next year will see moving JQuery core and open source licenses will be transferred to Software Freedom Law Center. Projects for the next year (think version 1.4) include move JQuery\UI infrastructure into JQuery proper. Significant work has been done within JQuery core to streamline and simplify plug-in development via the Widget Factory ($.widget(…)) (thanks to Scott González for this excellent presentation). For the hard core, Paul Irish gave an excellent presentation on JQuery Anti-Patterns. This was bookended by Yehuda Katz’s excellent Best Practices presentation. Aaron Quint was among the Rubists who are advancing the state of JQuery Art. His Sammy.js project attempts to use JQuery to create a browser side MVC/REST framework. John Nunemaker is also working in this basic area and his presentation can be found here.


The Jupiter Room


Photo By dlr2008 On FlickR.com

The walk away component demonstrated at the conference was the work done by Filament Group employees, Todd Parker and Scott Jehl who developed and maintain the new ThemeRoller CSS generator for use with JQuery/UI components. Outstanding Work!

This year’s conference was sold out at 300 participants and was a mind blowing experience. Two days of the sort of “deep dive” Microsoft presenters can only dream of. All this, plus great food and a T-shirt, for one hundred bucks American. We won’t see this sort of thing until the next big thing comes along. Look for the following event during 2010: one virtual (online) developer conference (similar to JQuery 2009 but without the food) and three ‘bigger’ user conferences (London, Los Angles and Boston). Splendid!

The AJAX Experience 2009

This conference took place at the Boston Airport Hilton on September 14 – 16, 2009. What an ugly hotel. Isolated, bad restaurant, overpriced breakfast, cold design, the hotel truly sucks. The conference itself was much better. If at JQuery 2009 we saw significant evidence of what the web will be in the next two years, The AJAX Experience showed us some of what will not happen:

  • The HTML5 specification will be released too late to mater,
  • ES5 will not change the world, or JavaScript.
  • Browser vendors will implement HTML5 using different API’s and approaches,
  • Conflicts between Security and JavaScript will NOT be resolved anytime soon,
  • JSON is not going away but XML ,
  • JavaScript is not going to be changed in any fundamental way,
  • Page Refreshes are not.

The AJAX Experience is a developer driven conference and uniquely includes presenters from both the standards community (W3C, ES5) and major players (Google, Facebook, Yahoo and Microsoft).


Douglas Crockford


Photo By dlr2008 On FlickR.com

The conference is well worth attending to take the pulse of the AJAX/REST world from a developer perspective. It is a conference with does not have an edge to it.  To be fair, this is a conference with a large number of big faces present and the structure of the conference is oriented towards making these faces easily available for one on one’s.  And for that we thank the folks at AJAX Experience.

On the plus side AJAX and REST continue to hold an enduring fascination for web developers looking for the edge. One of the best attended sessions was Facebook’s overview of how AJAX, careful architectural design, client side caching and REST principles, can be brought together into a workable whole. The presentation slides can be found here. This is an important presentation and should be viewed by anyone who want to ‘go all the way’ with AJAX/REST. If nothing else this presentation shows how little native support there is in the current set of browsers for this effort and how clumsy the basic design of JavaScript is when this advanced work is attempted. Please understand dear reader that the best AJAX/REST web site would have only ONE page load all other data exchange and UI work is done on this canvas. The Facebook folks found that after years of effort they still force unnecessary page loads as the only way to clean up events, timers, namespace debris and memory leaks.

Security

For me the most interesting, and the most depressing presentation was the much anticipated panel discussion: Secure Mashups: Getting to Safe Web Plug-ins

The panelists where Marcel Laverdet (Facebook – FBJS), Mike Samuel (Google – Caja), Scott Issacs (Microsoft – The Open Source Web Sandbox) and Douglas Crockford (adSafe). And the discussion was spirited. The goal here is to develop a method by which a web site (think Facebook for example) can accept browser widgets (think ads or user gadgets) from multiple sources and assure “secure cooperation” between all widgets and with the vendor’s (the page owner) HTML and JavaScript code. Although there are nuances between the different approaches and differences in scope, each of these attempts to mash-up ‘security’ follow the same pattern:

  • Clean incoming HTML for “evil parts”
  • Clean incoming JavaScript for “evil parts”
  • Encapsulate the remaining JavaScript code in wrapper functions which ultimately call methods in:
  • The Vendor’s Security Library

The Security Library purpose is to prevent, at run time, manipulation of HTML belonging to other parts of the system and preventing JavaScript exploits. Each solution provides its own definition of what the “evil parts” are, what constitutes ‘secure’ behavior and what are the limits of the security library. None of the solutions currently support JavaScript libraries. Although, Google and Microsoft made noises like they will attempt to bring third party libraries (read JQuery here) into the tent. There was a lot of discussion around this point. My notebook shows that John Resig’s name was mentioned by panelists eight times during this discussion. The overall goals of the projected solutions vary from forcing no code changes (Web Sandbox) to forcing complete re-writes (adSafe is alone is requiring safe widgets to being written exclusively using ONLY the adSafe library). All four projects are in early beta.
Significantly, there were no presentations which addressed Secure Browser OS projects like Microsoft Gazelle or Google’s Chrome OS.

PS: On the UI side of the house Bill Scott gave a delightful presentation on UI methods. For UI designers his presentations (and books) are not be to be missed.

JQuery And AJAX Experience 2009 – The Movie:



The JavaScript Singleton Pattern – Part III   Leave a comment





Jean Lafitte Swamp. Photo By dlr2008

The Singleton Saga – Part I
The Singleton Saga – Part II
The Singleton Sage – Part III

Welcome To Side Three.

The Singleton Pattern has been explored by Douglas Crockford among others. I first stumbled on the  Concept in a chapter of Harmes and Diaz’s book, Pro JavaScript Design Patterns. The Singleton Pattern is an anti-inheritance pattern. It is designed for situations where we which to create a single Component. For example, a Query String Reader Component is a good candidate to use the Singleton Pattern, since

  • The component makes little sense to have multiple Query String Readers on a single page;
  • the component is a good candidate for inclusion in a JavaScript support library;
  • The component can be created with no external side-effects or dependencies;

An bare bones abstract definition of a Query String Reader component might be given as:

  • The component is initialized with a reference to the query string location (i.e. location.search).
  • A public method could be defined as: (using C# syntax)
    • Public string GetValue(string Key);
      • This method returns the value associated with the Query String Key, or
        • Throws an exception if the Key is not found in the Query String.

In C# we might express this definition as

Public class QueryStringReader{
String  _OrigianlQueryString;//private string
Public QueryStringReader(string originalQueryString){..}// initialization step for this class
Public string GetValue(string key){…}
}

The Interface Definition for this object/class (in C#) might look like

Public interface iQueryStringReader{

String GetValue(string key);

}

What we would like to achieve in JavaScript is a component which roughly parallels these abstract

definitions. Note: I am using C# syntax here, because that my ‘native’ language. The abstract

definition expressed in Java is very similar. We will not build the QueryString Reader in this post.

By friend and coding associate, cle, is building one now using the singleton pattern. I promise to share

It with you when he is done. Interestingly, type “query string reader JavaScript” in your favorite

Search engine and you get about 500,000 hits! Instead, we will build a “talking dog” Singleton

Component. (With a talking dog, we don’t care so much about what the dog says, but that s/he talks at all). So let’s return to JavaScript now to do so.

Ok, so what do we want this talking dog to do? First let’s define the abstract features shared by all

Singleton Components:

  • Modular Design
    • no side effects or external dependencies
  • Namespace Minimization
    • The class requires, at most, one (page) global variable.
  • Private fields
    • internal fields (variables) which retain values between calling to the object
  • Private Methods
    • internal methods which can reference other private methods and fields
  • Public Methods
    • Multiple public methods, but
      • A limited set of non-contingent public methods
    • Public method which can reference private methods and fields
      • without using a context prefix (this or that)
      • See Part II of this series if this is unclear.
  • Does not use the JavaScript “new” verb
  • Supports an Instance Initialization method
    • ctor in C# terms
  • Clear separation of interface and implementation

[Note: I will use the terms function and method interchangeably in this post. One should remember

that function (methods) are actually full JavasScript Objects, with all that that implies.]

Now lets define the Talking Dog Component

  • Public Interface:
    • public iTalkingDog{
      void Speak();
      void Set(string WordToSpeak);
      }
  • Initialization:
    • Provide the first work to speak on initialization.
  • Behavior:
    • Set(string)
      • Sets the word to speak.
    • Speak()
      • Sends the word to speak to the alert box method.
  • Model Usage:
    Var talkingDog={magic code appears here}('bark');
    talkingDog.Speak();  //alertbox show: 'bark';

Show Us Some Code

var talkingDog=(
function(startupWord){
var _word=startupWord;
function _speak(arg){
alert(arg);
}
function _Set(arg){
_word=arg;
}
return{
Speak : function (){ return _speak(_word);},
Set : function(arg){ return _Set(arg);}
}
}
)('bark');
talkingDog.Speak();//bark
talkingDog.Set('Grrrr');
talkingDog.Speak();//Grrr

let’s break this down a bit. Start with the ZEN sequence

I. ZEN! Do Nothing but do it right now.

()();

II. More ZEN! Do Nothing and safe the results as an empty JavaScript Object

var doNothing=()();//but do it right now

Add an anonymous private method.

var privateThing=(function(){})();

Expanded with notes:

var privateThing=(
function(arg){//defines anonymous method here
}
)();

III. Store initialization argument object.

var doNothing=(
function(arg){//the anonymous method receives 'bark' as an argument
var _Word=arg;//and saves it for future reference
}
)('bark');

Still nothing visible or functional.

IV. Define a private named function within the outer anonymous function.

var doNothing=(
function(arg){//the anonymous private method, receives 'bark' as an argument
var _Word=arg;//and saves it for future reference
function _speak(arg){ //inner private function
alert(arg);//Display the contents of arg in an alert box
}
}
)('bark');

Still nothing visible or functional

IV. Define The Public Methods (aka The Public Interface)

var talkingDog=(
function(arg){
var _word=arg; 
 function _speak(arg){ 
 alert(arg); 
 }
return {//define  public method(s)
Speak : function (){ 
 return _speak(_word); 
}//end of public method: Speak
}//end of public interface
}//end of outer anonymous function
)('bark');
talkingDog.Speak();

The dog can speak, at last.





Jazz Fest Trio. Photo By dlr2008

Some Additional Technical Notes:

Composed this way, public methods can safely reference private fields and methods, directly and unambiguously. (say closure three times and click your heels) Public methods cannot safely reference other public methods. The syntax is triple tricky. The public interface (Redcode in Listing V) is JSON syntax( Separate JSON items with commas).

The private implementation (Green Code in Listing VI) are defined using normal JavaScript syntax (Separate statements with semi-colons). Green Code mixes executable code (var _word=arg;) with declarative code (function _speak(arg){…}).   Private methods may refer to other private methods and fields unambiguously.  Private methods can not reference public methods.

The (RED) Public Interface Section is basicallydeclarative and is evaluated when called (using the context of the anonymous method, not the context of the caller).

Magic Beans, for sure.

You’ve Been Warned.

dlr2008

The Singleton Saga – Part I
The Singleton Saga – Part II
The Singleton Sage – Part III

The JavaScript Singleton Pattern Part II   Leave a comment





Aveune Of The America NYC July 4th, 2009
By dlr2008

The Singleton Saga – Part I
The Singleton Saga – Part II
The Singleton Sage – Part III

Closures are one of the most powerful features of ECMAScript (JavaScript) but they cannot be property exploited without understanding them. They are, however, relatively easy to create, even accidentally, and their creation has potentially harmful consequences, particularly in some relatively common web browser environments. To avoid accidentally encountering the drawbacks and to take advantage of the benefits they offer it is necessary to understand their mechanism. This depends heavily on the role of scope chains in identifier resolution and so on the resolution of property names on objects.

In comp.lang.javascript FAQ

Most of what we will discuss today is taken from Crockford’s seminal essay on Private Fields And Closure. Please note: The current examples (and those in Crockford’s essay) depend on the use of the JavaScript “new” verb in order to ‘instantiate’ a JavaScript object. Crockford’s more recent work treats “new” as unsafe JavaScript. As such, his JSLint program will flag uses of new with warnings in its ‘strict’ mode. I, personally, don’t have a problem with “new” in JavaScript but we will not go into that debate here. Part III will introduce a non-“new” constructor method anyway.So, let’s begin.

Recall how private methods (aka inner methods) can be defined in an object:

1. function Container(param){
2.    return makeSmall(param);
3.     function makeSmall(arg){
4.          return arg.toLowerCase();
5.     }
6.  }
7. var out=Container('BIGFISH');

Nothing fancy here. Let’s look at this short code segment as the un-threaded JavaScript inturprature
looks at it.

  • Read line #1. Create a object called “Container” enclosed by brackets at line #1 and line#6.
  • Read lines #1 through #6, check for syntax and DO NOT EXECUTE any code.
  • Create an enclosure within Container called “makeSmall”. Lines #3 through #5
  • Read line #7, check for syntax and EXECUTE Container(‘BIGFISH’);
  • Execute line #2. To do so:
    • Execute the function makeSmall on line #3
    • Return the results of makeSmall as the results of the call to Container

the var “now” then contains the string ‘bigfish’

“makeSmall” is an inner method of Container ( Often called a private function by Crockford). In addition

to methods we can create private fields within an object with syntax like this:

function Container(param){
            var privateField;
}

“privateField” is, like “makeSmall” in the prior example, not visible outside of Container.

Public Methods and Fields At Last: Using “new” in JavaScript

Ok, we are almost there. Here is something that looks

like a class definition (but its not really). The following code is NOT executable by itself.

function Container(param) {
     function makeSmall(arg){
          return arg.toLowerCase();
    }
    var member = param;
    this.Service = function () {//use of "this" is required here
            return member;
        }
     this.PublicField='Everyone Sees Me, I hope';//use of "this" is required here.
}

In this container we have defined two private objects:

  • the private function: makeSmall; and
  • the private field: member; and

we have defined two public objects:

  • a public function: this.Service
  • a public field: this.PublicField

To use “Container” object we need to deploy the “new” verb:

var b=new Container2('abc');
alert(b.Service()); //this will return the string 'abc';

Note that Service is public and is defined using JSON syntax: this.Service = function(){…};

Crockfords notes that, defined this way, Service can only reference private members,

and fields within the Container object. We can do better, but we must work a little harder.

What is all this THIS and THAT stuff anyway?

We might try to create a global field by the following (improper) syntax:

1. function Container(param) {
2.    PublicField=param;
3. }
var b=new Container3('wow');

We can test the results by doing the following:

line 4. var c=b.PublicField;
line 5. var d=PublicField;

Variable “c” is now equal to ‘undefined’ (the type, not the string); and
Variable “d” is now equal to ‘wow’;

What went wrong here? Line # 2 defines PublicField as a global (within the current execution context)

The variable PublicField is  not associated in any way with Container. Container.PublicField is Not defined so the

attempted reference to it, via b.PublicField returns undefined.

All of this is expected and legal behavior, its just not the behavior we want. It seems like what we

want is a syntax which users the “this” key word. But this way there be dragons. The this key word

will also be used to allow our public and private functions to access public fields. Here is the code

first (more or less straight from Crockford) and more discussion follows the code.

function Container(param) {
    function dec() {
        if (privateField < 0) {
            privateField -= 1;
            return true;
        } else {
            return false;
        }
    }
   this.PublicField=param.toLowerCase();
    var member = param;
    var privateField = 3;
    var that = this;
    this.Service = function () {
        if (dec()) {
            return member;
        } else {
            return null;
        }
    };
    this.SpecialService = function () {
        if (dec()) {
            return that.PublicField;
        } else {
            return null;
        }
    };
}

//Testing:
var myContainer=new Container('FATCAT');
//var myContainer is now an object of type Container
var b=(new Container('FATCAT')).Service();             
//var b now equals 'FATCAT'
var c=(new Container('FATCAT')).SpecialService()      ;
// var c now equals 'fatcat'
var d=(new Container('FATCAT')).privateField      ;         
//var d now equals type 'undefined'

In this code we have the following:

Object

Type

Access

Notes

dec

Function

Private

This.PublicField

Field

Public

privateField

Field

Private

Private
fields are static within the derived object (i.e. var x=new Container(…);)

Member

Field

Private

that

Field

Private

Pointer
to the execution context in the Container object was instantiated. This
private field must be used within any private or public function to access
Public Fields and Functions. Note, that “that” must be set during object instantiation
only.

this.Special

Function

Public

This
function accesses only private fields.

This.SpecialService

Function

Public

This function accesses private functions and fields. It also access a public Field (that.PublicField).

Container is a JavaScript object but it can ONLY be used
with a “new” statement:

var myContainer=new Container('FATCAT');

Container is NOT a class definition (no such animal exists in JavaScript). Here is the walk through of code execution during a instantiation.


  • The object “myContainer” is instantiated as an instance of Container.
  • Function dec is defined but not executed.

  • · This.PublicField is defined and set to the lower case of the input parameter.

  • · member is defined and set to the original value of the input parameter.

  • · privateField is defined and set to the value of 3.

  • · “that” is defined and set to “this”. At this execution moment, “this” is equal to a pointer to the execution context where the object “a” is being created. JavaScript does not guarantee that the value of “this” will remain constant during the course of your program execution.  Please see the PS at the end of this blog for additional information.

  • · this.Special is defined and not executed.

  • · this.SpecialService is defined and not executed.

Ok, so much for this, that and the other thing. In the next post on this subject we will find a syntax to allow us to do away with the “new” verb and still get an object back in return.

PS

One additonal word about using the parttern:

var that=this;

The stratagy of using “that” is required when you need to make internal references to Public properties of the object.

From the above example if we are given:

   this.PublicField=param.toLowerCase();
   var that=this;
    this.SpecialService = function () {
        if (dec()) {
            return that.PublicField;
        } else {
            return null;
        }
    };

the reference to PublicField in:

return that.PublicField;

Requires the use of the that modifier. However references to private (internal) properties explicitly

require NOT using the “that.” modifier.

In the current example note how the function “dec” is coded:

function dec() {
        if (privateField < 0) {
            privateField -= 1;
            return true;
        } else {
            return false;
        }
    }

Well, now you have been warned.

Good Bye, And Good Luck

dlr2008

The Singleton Saga – Part I
The Singleton Saga – Part II
The Singleton Sage – Part III

Crockford On Javascript   Leave a comment


Swamp I – on LA 45 South (Near New Orleans)

Originally uploaded by dlr2008

Javascript is the only language people use without first learning the language.”

– Douglas Crockford

Sometimes called the Godfather of Javascript, Douglas Crockford is currently the premier authority on safe, effective Javascript.  If you use Javascript and have not seen: Javascript – The Good Parts Stop what you are doing and watch this presentation now. This is a great presentation of Crockfords mature thinking on Javascript. After working for years on advanced methods of inheritance in javascript he has moved beyond both Prototypal and Pseudoclassical inheritance.  Crockford currently recommends what he calls Parasitic Inheritiance (aka: the Power Constructor).  To get into all the details, including some dead ends which Crockford has explored try his presentation: Advanced Javascript.

I will be discussing Crockford’s use of Closures, the Singleton and the Power Constructor in the next few Javascript posts. Until then take a look at these presentations.  Your code will never be the same again.

Posted 2009/06/02 by Cloud2013 in Crockford, Javascript

Tagged with ,

%d bloggers like this: