I think this constructor could be a good start point for a lot of projects.
We know that IE has problems while it try to extend an array, disabling length modification.
That's why I have created this wrapper that does not require weird strategies (e.g. iframe with a different enviroment) and works with a wide range of browsers.
Honestly, I did not test performances against pure arrays, but I did everything to make code as fast as possible, using good practices and creating an in-scope shortcut for the Array.prototype.
Have a look here if you are interested in this constructor, ignore them if you do not think this is a good idea :)
P.S. Please note that this constructor does not care about missed prototypes, it only does its wrapping work and nothing else. To improve Array compatibility and methods, please remember my JSL Revision. Including them in your page, You'll not have problems with every ArrayObject method, eccept for reduce and reduceRight (I will create a good implementation of those function, I promise!)
behind the design
My JavaScript book is out!
Don't miss the opportunity to upgrade your beginner or average dev skills.
Sunday, March 02, 2008
Saturday, March 01, 2008
[COW] The fastest JavaScript rand ... isn't it ?
Hi guys, the WebReflection COW is a function that's so simple as usual: the php like rand function, to create random number, or random boolean evaluation:
What's new? Nothing, but could be useful :lol: ... and it has really good performances
Above example is for boolean assignment for random things
The function works as PHP one, creation of something casual apart.
I mean, if you use rand(), why don't you use Math.random() ?
So, basically, this function is to have a random number from 0 to N, where N is the min argument, or from min to max, where MAX is the second one.
Have a nice WE
function rand(min, max){
return max ? min + rand(max - min) : Math.random() * ++min << .5;
};
// pseudo packed version, 62 bytes
function rand(m,M){return M?m+rand(M-m):Math.random()*++m<<.5}
What's new? Nothing, but could be useful :lol: ... and it has really good performances
// boolean evaluation
var testMe = rand(1) ? true : false;
Above example is for boolean assignment for random things
The function works as PHP one, creation of something casual apart.
I mean, if you use rand(), why don't you use Math.random() ?
So, basically, this function is to have a random number from 0 to N, where N is the min argument, or from min to max, where MAX is the second one.
rand(2); // 0, 1 or 2
rand(2, 5); // 2, 3, 4 or 5
Have a nice WE
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:
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:
Here some example:
Press Run, and You'll read 123 on output panel.
Now press clear, and area will be without text.
Write again ...
Without the print, now press Add Before, area will be clean again ... BUT, write this:
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 :)
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.
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.
One way to solve scope problems betwen external prototype based methods and private constructor functions, is to use a bridge.
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:
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:
This list rappresents Create function goals:
This one rappresents Create function limits:
To better understand last point, look at this example:
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:
Enjoy my code and have fun with JavaScript!
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
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
Labels:
client,
compression,
CSS,
file,
JavaScript,
optimization,
packed.it,
server,
side,
single,
Web 2.0
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:
While these are two simple tests:
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)
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
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
Simple, quick, and dirty ;) and this is another example:
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
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? :)
This simple thing is present, for example, in jQuery.smile method.
Enjoy these tricks, and this week end as well :)
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
Use $("one or more smiles containers").smile(true or false) to add/remove smiles from your pages.
See you ;)
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.
Next post will be about my define function for jQuery, a typeOf suggestion, and finally JSmile integrated in jQuery ... so please, stay tuned :)
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 :)
Monday, January 21, 2008
JSmile ? Even more simple with an AntiPixel ;)
I've created an antipixel gif to add JSmile easily in your site too.
What should you do to add JSmile?
Copy and past this code wherever you like in your website.
<img
src="http://packed.it/JSmile/JSmile.gif"
alt="JSmile - by Web Reflection"
title="JSmile - by Web Reflection"
onclick="if(window.JSmile){JSmile(document.body)}else{var i=setInterval(function(){if(window.JSmile){clearInterval(i);JSmile(document.body)}},20),s=document.createElement('script');s.src='http://packed.it/JSmile/?js';document.body.appendChild(s)}"
/>
Done? Perceft, now when you want, click in JSmile antipixel and your site will be more rich.
Too simple? :o
Sunday, January 20, 2008
JSmile - smiles everywhere in less than 1Kb!
Update !
Now you can see JSmile in action directly in this blog ;)
I added just this line:
and the magic happened :D
Come on guys, we have totally unobtrusive smiles for blogspot and every other blog site too 8-)
P.S. script, code, pre, and noscript tags are preserved. No changes will be done by JSmile. If you think about another element that shouldn't be parsed, please tell me :geek:
----------------------------------------------------
Do you want to add some graphic smile in your site?
Do you like GTalk and you think that inline smiles should be cool for your website too?
Are you worried about obtrusive smiles?
Are you worried about server side parsers?
Are you worried about other libraries and JavaScript events for each element?
... forget everything and use JSmile, a new library in less than 1Kb (gzipped) that uses DOM instead of innerHTML, could be compatible with every other kind of library and add smiles using a single site, avoiding cache or bandwidth problems!
Do you want to try an example?
Go to this page: http://ajaxian.com/archives/winter-holiday-christmas-lights
Look at the text, you could find some smile like ;) ... now, if you use firefox, try to cut and copy this piece of code in your ulr:
Can you see the difference?
Text nodes are changed in a totally unobtrusive way.
No paranoia guys, a person without images will read alternative text, a person with image will read the title if they'll move mouse over the smile.
A person that use JS events can't be worried, events are for other kind of nodes, not for text nodes .... a person without JS enabled will see textual smile .... a person with JS enabled will see a smile using its cache, because of single url and unique smile identifier ... do you need more?
Ok, you should use this function wherever you want and choose wich part of your page should be parsed, sending simply dom node to JSmile function:
Seems interesting? This function could make your site cooler without any effort.
Include JSmile in your head tag and use JSmile function wherever you like.
Currently this function uses phpBB default postable smiles but in the future new smile themes will be available.
Enjoy JSmile and have fun with unobtrusive JavaScript!
Now you can see JSmile in action directly in this blog ;)
I added just this line:
// this element is smile free :)
// noone will be added in code or pre tags
JSmile(document.body);
and the magic happened :D
Come on guys, we have totally unobtrusive smiles for blogspot and every other blog site too 8-)
P.S. script, code, pre, and noscript tags are preserved. No changes will be done by JSmile. If you think about another element that shouldn't be parsed, please tell me :geek:
----------------------------------------------------
Do you want to add some graphic smile in your site?
Do you like GTalk and you think that inline smiles should be cool for your website too?
Are you worried about obtrusive smiles?
Are you worried about server side parsers?
Are you worried about other libraries and JavaScript events for each element?
... forget everything and use JSmile, a new library in less than 1Kb (gzipped) that uses DOM instead of innerHTML, could be compatible with every other kind of library and add smiles using a single site, avoiding cache or bandwidth problems!
Do you want to try an example?
Go to this page: http://ajaxian.com/archives/winter-holiday-christmas-lights
Look at the text, you could find some smile like ;) ... now, if you use firefox, try to cut and copy this piece of code in your ulr:
javascript:(function(){var script=document.createElement("script");script.src="http://packed.it/JSmile/?js";script.onload=function(){JSmile(document.body)};document.lastChild.appendChild(script)})();
Can you see the difference?
Text nodes are changed in a totally unobtrusive way.
No paranoia guys, a person without images will read alternative text, a person with image will read the title if they'll move mouse over the smile.
A person that use JS events can't be worried, events are for other kind of nodes, not for text nodes .... a person without JS enabled will see textual smile .... a person with JS enabled will see a smile using its cache, because of single url and unique smile identifier ... do you need more?
Ok, you should use this function wherever you want and choose wich part of your page should be parsed, sending simply dom node to JSmile function:
JSmile(document.getElementById("testMe"));
Seems interesting? This function could make your site cooler without any effort.
Include JSmile in your head tag and use JSmile function wherever you like.
Currently this function uses phpBB default postable smiles but in the future new smile themes will be available.
Enjoy JSmile and have fun with unobtrusive JavaScript!
Wednesday, January 02, 2008
PAMPA - On Line version 0.6
After few months without updates, I am proud to announce last version of my Portable AMP Application for Windows.
Changelog
You can find everything in the official PAMPA site.
Enjoy them :-)
P.S. I am sorry for possible server problems so please try later if You can't download or visit the official site.
Changelog
- New customizable tray icon, with different color for each status (active/unactive)
- New version of PHP, 5.2.5, with some extra dll active by default (APC and rfc for upload progres)
- New Apache 2.2.6 and MySQL 5.0.45 Comunity
- New options on system tray icon using right mouse button
- Removed TurbodbAdmin, added last version of phpMyAdmin by default some minor fixes or checks
You can find everything in the official PAMPA site.
Enjoy them :-)
P.S. I am sorry for possible server problems so please try later if You can't download or visit the official site.
Monday, December 31, 2007
[OT] Never forget old school!
Another year has gone, new technologies are coming but please never forget genuine old style. Happy new year to everyone from me and old "friend" :D
Saturday, December 29, 2007
Is JSON forgetting something?
I played many times with JSON serialized data, creating odd alternatives too like JSTONE or JSOMON.
Few years ago I created even a PHP compatible serializzation but nowadays, with PHP5, json_encode and json_decode are natively integrated in PHP language and, at the same time, even faster than old serialize and unserialize global functions.
Both JSON and PHP Serialized data have the same goal: transport objects and data over http protocol or storage these informations inside a cookie, a database or why not, a file.
However, PHP serialize and unserialize functions do more things than JSON serializzation, adding charset/indexes informations transporting even private or protected parameters.
With JavaScript 3rd edition We have not latter kind of properties so we shouldn't care about this limit during serializzation.
This is probably the most important difference between these two different serializzation but there is another one that should be easily implemented in JavaScript too: magic __sleep and __wakeup methods.
The most important information we need to make JSON more magic than ever should be the constructor name. Without this information every kind of instance will lose its special methods/properties reducing them as a common Object.
Usually, this is exactely what we would like to transport, keys and values or, in the case of Array, only its values.
I'm thinking about something like that:
I think that original objects doesn't need their constructor name.
In this way the unique change is for different instances and JSON syntax is quite the same.
With a string like that we should use eval too in a simple way:
The __wakeup magic method should be used to do something before the object will be assigned, extremely useful in a lot of common situations.
The magic __sleep method should be the same used with PHP.
A simple prototype that could do everything but that needs to return properties we want to serialize.
This should be a JSON parser problem that could check every instance and use, only if it's present, its __sleep method.
This is just a personal brainstorming/proposal and I would like to know what do you think about that.
P.S. marry Christmas and happy new year :-)
Few years ago I created even a PHP compatible serializzation but nowadays, with PHP5, json_encode and json_decode are natively integrated in PHP language and, at the same time, even faster than old serialize and unserialize global functions.
The big difference between JSON and PHP serializzation
Both JSON and PHP Serialized data have the same goal: transport objects and data over http protocol or storage these informations inside a cookie, a database or why not, a file.
However, PHP serialize and unserialize functions do more things than JSON serializzation, adding charset/indexes informations transporting even private or protected parameters.
With JavaScript 3rd edition We have not latter kind of properties so we shouldn't care about this limit during serializzation.
This is probably the most important difference between these two different serializzation but there is another one that should be easily implemented in JavaScript too: magic __sleep and __wakeup methods.
What do we need
The most important information we need to make JSON more magic than ever should be the constructor name. Without this information every kind of instance will lose its special methods/properties reducing them as a common Object.
Usually, this is exactely what we would like to transport, keys and values or, in the case of Array, only its values.
I'm thinking about something like that:
function A(){};
function B(){};
B.prototype.__wakeup = function(){
this.d = String.fromCharCode(this.c + this.a.charCodeAt(0));
};
var a = new A;
a.a = "b";
a.c = "d";
a.e = new B;
a.e.a = "b";
a.e.c = 3;
alert(encode(a));
// $("A",{"a":"b","c":"d","e":$("B",{"a":"b","c":3})})
I think that original objects doesn't need their constructor name.
In this way the unique change is for different instances and JSON syntax is quite the same.
With a string like that we should use eval too in a simple way:
function decode(str){
function $(constructor, o){
var result = eval("new ".concat(constructor)), key;
for(key in o){
if(o.hasOwnProperty(key))
result[key] = o[key];
};
if(typeof result.__wakeup === "function")
result.__wakeup();
return result;
};
return eval(str);
};
function A(){};
function B(){};
B.prototype.__wakeup = function(){
this.d = String.fromCharCode(this.c + this.a.charCodeAt(0));
};
var o = decode('$("A",{"a":"b","c":"d","e":$("B",{"a":"b","c":3})})');
alert([o instanceof A, o.e instanceof B, o.e.d]);
The __wakeup magic method should be used to do something before the object will be assigned, extremely useful in a lot of common situations.
What about __sleep?
The magic __sleep method should be the same used with PHP.
A simple prototype that could do everything but that needs to return properties we want to serialize.
This should be a JSON parser problem that could check every instance and use, only if it's present, its __sleep method.
Improvements
- constructor name for instances that are not just objects
- better server side parsers to manage instances without loosing their constructor name
- a global name for dollar function, if some library use them as constructor too to avoid problems during instance creation (or a simple global-scope evaluation for each new "constructor" assignment)
This is just a personal brainstorming/proposal and I would like to know what do you think about that.
P.S. marry Christmas and happy new year :-)
Friday, December 21, 2007
JavaScript Iterator for IE and other browsers
This is just my proposal to add Iterator in Internet Explorer and other browsers too.
The best way to use them is with iter.next() method but you could use a for in loop too.
However, in latter case if the object has a next property, it will be overwrote by dynamic method but this problem apart, enjoy iterators :-)
(function(){
function Iterator(obj, name){
// Iterator(obj) and new Iterator(obj) behaviour
if(this instanceof Iterator){
var i = 0,
result = [],
skip = false,
key;
for(key in obj){
result[i++] = name ? key : [key, obj[key]];
this[key] = undefined;
if(!skip && (key == "constructor" || key == "toString" || key == "valueOf"))
skip = true;
};
// solve IE problems
for(var l = 0, arr = ["constructor", "toString", "valueOf"]; !skip && obj.hasOwnProperty && l < arr.length; l++){
if(obj.hasOwnProperty(arr[l])){
result[i++] = name ? arr[l] : [arr[l], obj[arr[l]]];
this[arr[l]] = undefined;
};
};
// add next method if any next in object
this.next = function(){
if(i === result.length)
throw new StopIteration;
else
return result[i++];
};
// reset result "pointer"
i = 0;
}
else
return new Iterator(obj, !!name);
};
function StopIteration(message, fileName, lineNumber){
this.message = message;
this.fileName = fileName;
this.lineNumber = lineNumber;
};
StopIteration.prototype = new Error;
// global scope check
if(!this.Iterator)
this.Iterator = Iterator;
if(!this.StopIteration)
this.StopIteration = StopIteration;
})();
// test it!
var iter = Iterator({a:"b", next:"c", toString:"hello"}),
output = [];
try{
while(true)
output.push(iter.next());
}
catch(err){
if(err instanceof StopIteration)
output.push("End of record");
else
output.push("Unknown error: " + err.description);
};
alert(output.join("\n"));
The best way to use them is with iter.next() method but you could use a for in loop too.
However, in latter case if the object has a next property, it will be overwrote by dynamic method but this problem apart, enjoy iterators :-)
Thursday, December 20, 2007
packed.it ... again online
I am sorry for last days while packed.it wasn't working as expected because of new server.
It seems to be faster than precedent one so thank you again Daniele, I'll write your link as soon as I can :-)
Enjoy both JavaScript and CSS compressed files in a single one, enjoy packed.it!
It seems to be faster than precedent one so thank you again Daniele
Enjoy both JavaScript and CSS compressed files in a single one, enjoy packed.it!
Monday, December 10, 2007
FireFox, Safari, and Opera ... JavaScript Conditional Comment
I've still written a comment in John Resig blog about Re-Securing JSON and FireFox or Safari 3 const behaviour to create an immutable function, called Native, and to retrieve original Array, Object, String or other constructors.
This is the function:
At the same time I've talked about IE behaviour and its missed support for const.
While I was thinking about that I imagined a way to use a piece of code, in this case the keyword const, compatible with every browser.
It should sounds simple, just use the well know trick IE=/*@cc_on ! @*/false; followed by if(IE) ... but ... hey, I need everytime to create a double version of the "same script" ... is it good?
Try to imagine a variable that should be a constant for every compatible browser but at the same time should be declared just one time ...
With every day practices we should use a try catch or some strange trick to evaluate a const declaration ... don't we?
But we have a particular behaviour of the conditional comment ... it should contains a comment itself too, sounds cool?
Can anyone trigger an error with above piece of code? :-)
In this way FireFox 2+, Safari 3+ (I don't know about 2), and Opera 9+ could work without problems disabling Native variable re-declaration while every IE browser will ignore the const keyword.
I suppose this trick is not so new but never as this time it should be useful to make code more slim and efficient.
Instant Update
The usage of const inside the private scope of Native function declaration is not so useful (just a little bit of paranoia :D) but in these cases we could use a better trick to create local variables with internet explorer too.
This is an example:
Above example shows how should be possible to initializzate multiple variables using a comma and respecting the private scope.
Internet Explorer will use var while every other browser will try to use const if it's compatible.
Sounds even better? I hope so :-)
P.S. Native function is quite interesting, imho, that's why I choosed to add them in devpro.it
This is the function:
const Native = (function(){
const NArray = Array,
NBoolean = Boolean,
NDate = Date,
NError = Error,
NMath = Math,
NNumber = Number,
NObject = Object,
NRegExp = RegExp,
NString = String;
return function(Native){
switch(Native){
case Array:return NArray;
case Boolean:return NBoolean;
case Date:return NDate;
case Error:return NError;
case Math:return NMath;
case Number:return NNumber;
case Object:return NObject;
case RegExp:return NRegExp;
case String:return NString;
};
};
})();
// Example
Array = Native(Array);
eval("[1,2,3]");
At the same time I've talked about IE behaviour and its missed support for const.
While I was thinking about that I imagined a way to use a piece of code, in this case the keyword const, compatible with every browser.
It should sounds simple, just use the well know trick IE=/*@cc_on ! @*/false; followed by if(IE) ... but ... hey, I need everytime to create a double version of the "same script" ... is it good?
Try to imagine a variable that should be a constant for every compatible browser but at the same time should be declared just one time ...
const MyConstant = 1;
With every day practices we should use a try catch or some strange trick to evaluate a const declaration ... don't we?
But we have a particular behaviour of the conditional comment ... it should contains a comment itself too, sounds cool?
/*@cc_on // @*/ const
Native = function(){
// whatever You need
};
Can anyone trigger an error with above piece of code? :-)
In this way FireFox 2+, Safari 3+ (I don't know about 2), and Opera 9+ could work without problems disabling Native variable re-declaration while every IE browser will ignore the const keyword.
I suppose this trick is not so new but never as this time it should be useful to make code more slim and efficient.
Instant Update
The usage of const inside the private scope of Native function declaration is not so useful (just a little bit of paranoia :D) but in these cases we could use a better trick to create local variables with internet explorer too.
This is an example:
Native = (function(){
/*@cc_on var // @*/ const
NArray = Array,
NBoolean = Boolean;
return function(Native){
return Native === Array ? Narray : NBoolean;
};
})();
Above example shows how should be possible to initializzate multiple variables using a comma and respecting the private scope.
Internet Explorer will use var while every other browser will try to use const if it's compatible.
Sounds even better? I hope so :-)
P.S. Native function is quite interesting, imho, that's why I choosed to add them in devpro.it
Wednesday, December 05, 2007
Looking for a job in London ... or not?
It's about 2 weeks that I'm studying in London to improve my English knowledge, specially my spoken one (I know, written is not so perfect too).
I put my cv on line in a famous recluting search engine but it seems that most interested people are Agency's employees that usually look for generic IT - Web masters.
I would like to explain my "strange situation": I am not absolutely a web designer, I do know quite nothing about graphic, I could just know how to start Gimp!!! :D
It seems that if You know quite perfectly ActionScript 1.0/2.0, that's basically ECMAScript 3rd edition or, in case of 2.0, 4th one closed, you can be only a Web Designer and not a programmer, even if You know Flash Player bugs and you're able to find out workarounds.
It seems that if You know deeply JavaScript (best practices, OOP, Ajax, cross-browser/platform development, bugs, common libraries suggestions) it's not important ... just a preferred plus ... but at the same time everybody is looking for Ajax and Web 2.0 skilled developers, a role that absolutely requires a good programming background (not just a bit of DreamWeaver).
It seems that if you know different languages or technologies ... there's always a missed one.
How can a person to be "senior in every program language"?
I can't call their "expert or senior everything developers", a part for someone who has at least 20 years or more experience.
However, excellent OO PHP 4/5,JavaScript,ActionScript,(x)HTML,CSS,XML skills aren't enough while a good knowledge of C# for ASP.NET or MONO, and Python is not enough as a technical plus.
Maybe someone should be interested in my good database skills, starting from SQLite 2/3 to MySQL 3/4/5, passing inside PostgresSQL ... but it's not enough.
What about security practices and code optimization skills? Who cares about that!
As sum, and as someone said before me: please hire me !!! :-)
Best regards,
Andrea Giammarchi
I put my cv on line in a famous recluting search engine but it seems that most interested people are Agency's employees that usually look for generic IT - Web masters.
I would like to explain my "strange situation": I am not absolutely a web designer, I do know quite nothing about graphic, I could just know how to start Gimp!!! :D
It seems that if You know quite perfectly ActionScript 1.0/2.0, that's basically ECMAScript 3rd edition or, in case of 2.0, 4th one closed, you can be only a Web Designer and not a programmer, even if You know Flash Player bugs and you're able to find out workarounds.
It seems that if You know deeply JavaScript (best practices, OOP, Ajax, cross-browser/platform development, bugs, common libraries suggestions) it's not important ... just a preferred plus ... but at the same time everybody is looking for Ajax and Web 2.0 skilled developers, a role that absolutely requires a good programming background (not just a bit of DreamWeaver).
It seems that if you know different languages or technologies ... there's always a missed one.
How can a person to be "senior in every program language"?
I can't call their "expert or senior everything developers", a part for someone who has at least 20 years or more experience.
However, excellent OO PHP 4/5,JavaScript,ActionScript,(x)HTML,CSS,XML skills aren't enough while a good knowledge of C# for ASP.NET or MONO, and Python is not enough as a technical plus.
Maybe someone should be interested in my good database skills, starting from SQLite 2/3 to MySQL 3/4/5, passing inside PostgresSQL ... but it's not enough.
What about security practices and code optimization skills? Who cares about that!
As sum, and as someone said before me: please hire me !!! :-)
Best regards,
Andrea Giammarchi
Thursday, November 01, 2007
A quite totally standard enviroment before ECMAScript 4th Edition in less than 3Kb - JSL 1.8+
JavaScript Standard Library Revision
After the success of my old JSL project I learned more about JavaScript and I found some trick to solve different problems such setInterval and extra arguments for Internt Explorer, a function to evaluate code in a global scope with every browser as Internet Explorer does with its proprietary execScript.
Since these days We're waiting for ECMAScript 4th Edition, aka JavaScript 2 but since We always don't know when it should be really usable within productions, I choosed to create a revisited version of JavaScript Standard Library.
I removed Internet Explorer 4 support but I modified a lot of common prototyes to make them faster, more standard and more scalable than ever.
You can use, for example, every JS 1.6+ Array.prototype with HTMLCollections too as it's possible from many Years with FireFox or Safari:
Array.prototype.forEach.call(document.getElementsByTagName("div"), function(node){
alert(node.innerHTML);
});
I fixed different standard behaviours and I implemented setTimeout and setInterval.
I add execScript, not standard, but really useful when You need to evaluate JavaScript in a global scope with FireFox, Safari, Opera and every other as Internet Explorer does from many years with its own execScript global function.
JSL creates a quite totally standard JavaScript 1.6+ enviroment adding prototypes only to browsers that don't support them or that have different behaviours and everything in a hilarious size of
With JSL You can forget your own not always standard prototypes implementations so every library size could decrease its code quickly, basing them on standard JavaScript 1.6+ enviroment and increasing performances for every standard browser like FireFox or Safari (about 40% of users ... growing up every day!).
This is the last chance to have a more standard Internet Explorer implementation because if We need to wait their fixes We should go better to sleep.
Have fun with JSL Revision and a quite real ECMAScript 3rd Edition enviroment.
Subscribe to:
Posts (Atom)