My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, February 27, 2008

[ES4] ... too horrible to be an editor ...

... but probably simple enough for these milestones.

Its name is ES4me, it's for windows and works in this way:

  • download the file in your es4 folder, where there is the run.exe and the es4.bat file

  • double click



Basically, there is a place to write something, where for some reason TABS are usable only with CTRL + TAB instead of single TAB key, a panel where errors or output will be showed, and finally, 5 buttons:

  • Run, to execute the code

  • Clear, to clear the code in the area

  • Add Before, to add area code before execution

  • Get Before, to add in area the code added before

  • Clear Before, to clear content added before



Here some example:

var i:int = 123;
print(i);

Press Run, and You'll read 123 on output panel.
Now press clear, and area will be without text.
Write again ...

var i:int = 123;

Without the print, now press Add Before, area will be clean again ... BUT, write this:

print(i);

and press Run, you'll read 123 in the output panel.
This mean that precedent code is in ram, and is present on output but not in the area.
Of course, if you Add Before print(i); , this will be executed after var i:int = 123;

This is useful to add classes or other scripts, just tested.
Now, if you press Get Before, the entire content will be added to the area, after current one, if any.

Finally, with Clear Before, everything in the Ram will be cleaned.

Simple? Last thing: every time you press Run, code is compiled in a new enviroment.

That's it, and sorry for this horrible debugger ... but time is never enough :)

Sunday, February 24, 2008

How to inject protected methods in JavaScript

As you know, JavaScript requires different strategies to emulate private methods.
I personally wrote some weird experiment to automatically emulate private scope behaviour.

However, my experiment was RegExp based ... a really bad way to emulate private scope behaviour for a lot of reasons.

At the same time, you can implement private scope methods only inside the constructor and this means that you cannot base your code with both prototype and private scope.

// non sense example
function MyConstructor(value){

function privateMethod(){
return this.value;
}

this.get = function(){
return privateMethod.call(this);
}

this.value = value;
};

MyConstructor.prototype.getAgain = function(){
return privateMethod.call(this);
// error, privateMethod has a different scope
};


Basically, the reason that make prototype better than constructor with privileged methods, as get one is, is that core doesn't need to parse and/or create functions for each instance.
Another reason to prefer them is that you can add, remove, or change, a single function affecting every instance.
A good behaviour specially with a browser based language, as JavaScript is, that allow developers to write dedicated browser methods once, instead of check and change behaviour each time and for each instance.


The bridge strategy


One way to solve scope problems betwen external prototype based methods and private constructor functions, is to use a bridge.

// basic bridge example
function MyConstructor(value){

function privateMethod(){
return this.value;
};

this.callPrivateMethod = function(name, arguments){
return eval(name).apply(this, arguments);
};

this.value = value;
};

MyConstructor.prototype.get = function(){
return this.callPrivateMethod("privateMethod", arguments);
};

var demo = new MyConstructor("test");
alert(demo.get()); // test

Basically, the bridge method is a privileged wrapper, but it is inside the correct scope and that's why it can call function privateMethod without errors.
Seems cool? But it isn't so cool .. and that's why:

  • the bridge method is public, everyone could override them in every other place and for every instance

  • each instance creates every private function plus a bridge method, there's no prototype behaviour

  • last but not least, we are using eval ... and this means, for 99% of times, that we are using a bad code design



Public methods overload strategy


A different way to solve this problem is to inject your private methods inside the instance each time you call a public one.
You can do it once, and forget private scope methods for ever, using them in a natural way inside every other one.
To do it, you need to change at least one time each public method, overloading them during constructor assignment.
This is a final result example:

MyClass = Create(

// constructor
function(value){
this.value = value;
},{
// one or more prototypes
sum:function(num){
return this._checkNumAndSum(num);
}
},{
// one or more private methods
_checkNumAndSum:function(num){
alert(this.sum === MyClass.prototype.sum); // true
return typeof num === "number" && isFinite(num) ? this.value += num : undefined;
}
}
);

var demo = new MyClass(3);
alert(demo._checkNumAndSum); // undefined
alert(demo.sum(2)); // alert true and after them returned value is 5
alert(demo._checkNumAndSum); // undefined

This list rappresents Create function goals:

  • prototype based, it overloads directly the prototype object and it does not create protected functions each time

  • natural code, you do not need to change your code as is for bridge, during protected method execution


This one rappresents Create function limits:

  • you cannot share a prototype object, even if this phrase doesn't make sense for most of you

  • public methods execution time will be a bit slower, where that "bit" is not a real problem but for performances maniacs it will

  • injected methods are protected and not private, these are visible during method execution itself


To better understand last point, look at this example:

function visibleMethod(instance){
alert(instance._checkNumAndSum);
};

// ... same code of precedent example with this change

// one or more prototypes
sum:function(num){
visibleMethod(this);
return this._checkNumAndSum(num);
}


Since I guess that above situation is not so common, I think that's a good thing to let you know that protected methods are visible during each protected or public method execution.
Pure OOP has a different meaning for protected methods, it is based on possibility to use those methods from a subclass.
In my case, I choosed protected word because private one, usually not accessible from subclasses, is a word that loose its concept in the instant you can access that method outside the object.
I know probably my choice wasn't so serious, but for a prototype based inheritance I think it makes sense :)

Finally, what you really need to test my examples, is this function:

function Create(constructor, prototype, protected){
// (C) Andrea Giammarchi - Mit Style License
switch(typeof protected){
case "object":
var list = [],
i = 0,
key;
for(key in protected)
if(protected.hasOwnProperty(key))
list[i++] = {key:key, callback:protected[key]};
for(var key in prototype)
if(prototype.hasOwnProperty(key))
prototype[key] = (function(prototype){
return function(){
for(var i = 0, length = list.length; i < length; i++)
this[list[i].key] = list[i].callback;
result = prototype.apply(this, arguments);
while(i--)
delete this[list[i].key];
return result;
}
})(prototype[key]);
default:
constructor.prototype = prototype;
break;
}
return constructor;
};

Enjoy my code and have fun with JavaScript!

Wednesday, February 20, 2008

packed.it goes off line !

... or, to be honest, that's what it's gonna do in few days, but PHP version is out!

You can find every information about server side version of packed it directly in this page.

I am not joking when I said that packed.it is probably the fastest optimized client files server you can find over the net, even with an uncompiled program language like PHP.

The key is the JOT compiler, compile one time, serve all the time without paranoia, saving bandwidth for both server and client, avoiding the usage of gz handlers, avoiding runtime compression, avoiding whathever you want, and finally, having the possibility to serve js, css, or both with a single file.

Discover by yourself how long server need to serve, for example, jQuery ... less than one millisecond without louds of requests ... please look at X-Served-In header, if you do not trust me :P

What's new? You do not need to pass in packed.it site to compile your projects, you can just serve and compile them directly from your one.

To Do:
Python PSP and SWGI version, C# version and finally, Jaxter version for server side JavaScript auto compilation in itself language ... does it sound good?

Enjoy packed.it, and please do not ignore totally PayPal Donation :D

Cheers

Tuesday, February 19, 2008

[PHP] PartialFunction and PartialMethod

I found really interesting this John Resig post, about partial functions in JavaScript.

For a weird problem, I choosed to use the same behaviour, but with a different language: PHP

Sometime PHP is more flexible than we think (at least me), and this is the result of my little experiment:

class ReflectionPartialFunction extends ReflectionFunction {

protected $args;

public function __construct($name){
parent::__construct($name);
$this->args = func_get_args();
array_splice($this->args, 0, 1);
}

public function invoke($args){
$args = func_get_args();
return $this->invokeArgs($args);
}

public function invokeArgs(array $args){
return parent::invokeArgs(array_merge($args, $this->args));
}

public function rinvoke($args){
$args = func_get_args();
return $this->rinvokeArgs($args);
}

public function rinvokeArgs(array $args){
return parent::invokeArgs(array_merge($this->args, $args));
}
}

class ReflectionPartialMethod extends ReflectionMethod {

protected $args;

public function __construct($class, $name){
parent::__construct($class, $name);
$this->args = func_get_args();
array_splice($this->args, 0, 2);
}

public function invoke($object, $args){
$args = func_get_args();
return $this->invokeArgs(array_shift($args), $args);
}

public function invokeArgs($object, array $args){
return parent::invokeArgs($object, array_merge($args, $this->args));
}

public function rinvoke($object, $args){
$args = func_get_args();
return $this->rinvokeArgs(array_shift($args), $args);
}

public function rinvokeArgs($object, array $args){
return parent::invokeArgs($object, array_merge($this->args, $args));
}
}


While these are two simple tests:

function mul($num, $fixedParam = 0){
return $fixedParam * $num;
}

class Test{
protected $num;
public function __construct($num){
$this->num = $num;
}
public function me($num, $fixedParam = 1){
return $this->num * $fixedParam * $num;
}
}

$partial = new ReflectionPartialFunction('mul', 12);
echo $partial->invoke(2); // 24

$partial = new ReflectionPartialMethod('Test', 'me', 12);
echo $partial->invoke(new Test(2), 2); // 48


Now it's your round to find real applications ;)

update
Honestly, I need right arguments and my first implementation put partial arguments before the others and not at the end.

With this update you can use, by default, argments at the end of the function, but if you want to use them before, just call rinvoke or rinvokeArgs (r means put recieved arguments, during invoke or invokeArgs, on the right, at the end)

function mul($paramFixed, $num){
return $paramFixed / $num;
}
$ref = new ReflectionPartialFunction('mul', 4);
echo $ref->rinvoke(2); // will be 2, as 4 / 2

Wednesday, February 13, 2008

jQuery + jQuery UI + Full Flora Theme ... less than 32Kb

Don't You trust me? It's so diabolically simple with packed.it ... and more than a professional Web Developer complained about "why on heart noone talk about that service" :D

It's not packer, it's not YUICompressor, It's the only one that cache both CSS and JavaScript in a single file ... it's for PHP4, PHP5, Python wsgi, Python psp, C#.NET ... so, what are you waiting for?

Ok, I'll let you try this full package:
jQuery 1.2.3 and jQuery UI 1.5b with full Flora Theme included.

Enjoy ;)

P.S. jQueryUI.html example file calls jQueryUI.php, jut change estension in your server if you want python or .NET

Saturday, February 09, 2008

The fastest way to know if someone "did it" ...

I know I choosed a weird title, isn't it :?

Today I have two small and useful tips and tricks for JavaScript.

The first one, lets you know if someone extended the Object.prototype

if((function(k){for(k in {})return true;return false})()){
// do stuff that care about Object prototype
} else {
// do stuff that doesn't care about Object prototypes
}

Simple, quick, and dirty ;) and this is another example:

function didIt(k){for(k in {})return true;return false};

if(didIt()){
// stuff prototype
}

One thing to take care about is the usage of a function instead of a variable.
Since some script could run other scripts dinamically, you can't trust in a single time check.

The second trick is really useful for function that accept a switcher argument.
For switcher argument I mean methods or function that accept true or false as argument.
The simplest way to have a switcher is obviously sending the value, but in this case we can't have a default behaviour.

Simple is to choose a "false" behaviour as default one

function addOrRemoveStuff(dontDoIt){
if(dontDoIt){
// someone sent a true value
} else {
// default behaviour, dontDoIt is false or undefined
}
}


So what's new? Nothing, yet, but try to guess about a different default ... a true value as default ... think ... think ... think ... did you find them? :)

function addOrRemoveStuff(doIt){
doIt = !arguments.length || !!doIt;
if(doIt){
// default behaviour, doIt is true
} else {
// someone sent a false value
}
};

addOrRemoveStuff(); // true
addOrRemoveStuff(false); // false
addOrRemoveStuff(1); // true


This simple thing is present, for example, in jQuery.smile method.

$("div.post, p.comments").smile(); // add smiles
$("div.post, p.comments").smile(false); // remove smiles

Enjoy these tricks, and this week end as well :)

Thursday, February 07, 2008

JSmile for jQuery ;)

As I said one post ago, I've created a jQuery dedicated version of my simple JSmile project :geek:

Here you can find the demo page, qhle here the automatic generated source

What's new?
It's so simple

$(function(){
$(document.body).smile();
});


Use $("one or more smiles containers").smile(true or false) to add/remove smiles from your pages.

See you ;)

jQuery minor improvements

Update
This post has an "official" link, now, directly in devpro :)
--------------

These are just few fixes / improvements of some jQuery stuff.


(function(o){for(var k in o)jQuery[k] = o[k]})({

// IMPROVED: Evalulates a script in a global context using a specified JS version, if any
globalEval: function( data, version ) {
/** Examples
$.globalEval("let(a = 1)alert(a);"); // error
$.globalEval("let(a = 1)alert(a);", 1.7); // OK, alert 1

(function(){
var test = 1;
$.globalEval("test = 2");
alert(test); // 1
})();
alert(test); // 2
*/
data = jQuery.trim( data );
if ( data ) {
var script = document.createElement("script");
script.type = "text/javascript";
if ( version )
script.type += ";version=" + version;
if ( jQuery.browser.msie )
script.text = data;
else
script.appendChild( document.createTextNode( data ) );
with(document.getElementsByTagName("head")[0] || document.documentElement)
removeChild( appendChild( script ) );
}
},

// IMPROVED: optional strict comparation
inArray: function( elem, array, deep ) {
for ( var i = 0, length = array.length; i < length; i++ )
if ( (deep && array[ i ] === elem) || (!deep && array[ i ] == elem) )
return i;

return -1;
},

// FIXED: ( typeof array != "array" ) .... excuse me ???
makeArray: function( array ) {
if(array instanceof Array)
var ret = array.slice();
else
for(var ret = [], i = 0, length = array.length; i < length; i++)
ret[i] = array[i];
return ret;
}

});


Next post will be about my define function for jQuery, a typeOf suggestion, and finally JSmile integrated in jQuery ... so please, stay tuned :)