Visualizzazione post con etichetta javascript. Mostra tutti i post
Visualizzazione post con etichetta javascript. Mostra tutti i post

domenica, ottobre 09, 2011

MooTools private pattern mutator

UPDATE: I created a MooTools forge repository for Private. There you will find any kind of improvement ;) /UPDATE Not too long ago I wrote this gist to add a sort of private properties / private methods to MooTools 1.2.x:

As of MooTools 1.3 this gist won't work anymore, but I've wrote another one as alternative, it requires Mark Obcena's PatternMutators.js that you can find here: keeto.PatternMutators.js:
How it works?

In the first version, the one for the 1.2.x branch of MooTools, if you Implements Private, what happens under the hood is that it create a property using MooTools $uid to get a unique-id per istance on a not-accessible outside of Class.Mutators.Private function, then it rewrote all the method of your instance passing the associated property as the last parameter of your function so that you can use it to store/retrieve private properties or even methods.

Since there's no way to automate the cleaning of all the objects/methods you can add, it need also to add a '~' method that you need to call on your destructor so it will not leak memory. I decided to use this ugly syntax: ['~']() because it need to stand out of your code, in a way to remember you that you are using an ugly hack to create privates and because is easier to remember something so strange ;)

For the 1.3 and upper branches of MooTools(yep, still work on 1.4.x) I decided to use a different, not compatible, way to achieve the same objective, so I based my mutators on keeto's patternMutator, for a number of reasons, basically cleaner syntax, re-using of existing code (keeto's one), and only methods marked with 'private' are now overwritten. You can see an example right here:

The code is slighly different, instead of Implements:[Private], you have to explicity mark the method you would like to use private properties or methods by adding 'private ' ahead of your method name, but other things remains unchanged.

martedì, gennaio 22, 2008

[jsn]A simple JS IoC example code

Inspired by Ninject documentation I decided to port the c# example code to my JS IoC.
Here are the code:

var
shuriken = {
hit:function(who){alert("pierced the "+who+" armor");}
},

sword = {
hit:function(who){alert("Chopped the "+who+" in half");}
};

function Samurai(weapon){
return {
Attack:function(who){
weapon.hit(who);
}
}
}
container.register("samurai",Samurai);
var warrior1 = container.byConstructor("samurai",shuriken),
warrior2 = container.byConstructor("samurai",sword);

warrior1.Attack("The evildoers");
warrior2.Attack("The evildoers");


So simple, So clear!

[jsn]JS IoC on GoogleCode!

Today I moved my JS IoC source on GoogleCode,
and for the occasion i made a little change in the code, so now JS IoC
is perfectly compatible with MooTools ( I tested the beta, but it should work on the current also ) with the Class Module selected.
So now you have 2 choice, or use the old (and perfectly working) code and use
Andrea Giammarchi extend script (I put that also on Google Code) or if you
already use MooTools you can simply take the 1.0MT version and you're ready to go!

lunedì, ottobre 29, 2007

[jsn]getElementByClass revisited

Today me and my friends Andr3a had a talk about getElementsByClassName,
I had the idea to write my own implementation since 1 year ago,
in that time I first saw firefox document.evaluate and I blogged to remind myself that I must wrote a better implementation.
The original one was based on Dustin Diaz works.
Seems that the day is come for me, so I've taken my previous work and i've done a lot of optimization, i think now is one of the fastest that you can find around the net
...here the code:


getElementsByClassName.js

/*Kentaromiura 1.0 version*/
document.getElementsByClassName = function(searchClass,tag,node){
var p = function(){
if([].push)return function(a,b){a.push(b)};
return function(a,b){a[a.length]=b}
}();

node = node || document;
tag = tag || '*';

if(document.evaluate){
var xpr = document.evaluate([".//",tag,"[contains(concat(' ',@class,' '),' ",searchClass," ')]"].join(''),node, null, 0, null),
t = true,
els = new Array();
while(t=xpr.iterateNext()){
p(els,t);
}
return els;
}


var els = node.getElementsByTagName(tag),
pattern = new RegExp(["(^|\\s)",searchClass,"(\\s|$)"].join('')),
ce = new Array();

for (var i = 0, max = els.length; i < max; i++) {
if(pattern.test(els[i].className))
p(ce,els[i]);
}
return ce;
}


Tomorrow I will test it more, for now i only can say that it will work on
IE7, FF 2.0.x.x and safari 3.0.3
Teoretically it should work with IE4+, NN 7+,opera 8+ ff 1+ but keep this as not sure
since I can't test it right now.
So if you can leave a comment with your browser I would be grateful.

Ps. since I share my ideas with andr3a, he had wrote his own implementation,
it is very similar to my approach but it's different in some way, so be sure to take a look at his work

bye ;D

martedì, settembre 04, 2007

KentaIoC - A js IOC library - english version


Thanks to Rey9999 for this marvelous translation.
original document here: Italian version



I've been lately using an IOC framework at my workplace and I grasp the potential of such an approach right from the start, since it lets you keep your classes conceptually separated. 

To achieve this, we follow a single concept: keep the logic that binds the classes together outside of those classes.

Often, in traditional programming, an object "A" inside a method configures another object "B", before calling some other method of the latter.

With Inversion of Control instead, object "A" will never need to configure object "B", instead it will just call it directly.

Probably I was not clear enough, so I invite whoever wishes to understand better this topic to study it deeply elsewhere - I will now pragmatically focus on writing some code which will let us use IOC in JavaScript.


How do we set up IOC?

Usually we have a class "A", keeping inside a member "B" extending a known interface: this way, even if "A" does not know the actual implementation of "B", it can communicate with it, as between "A" and "B" there's a kind of "contract" defined by the interface.

Sure, but in Javascript there are no interfaces, so programming through interfaces is impossible!


Of course, this is the first problem that I will write about.
Let me first point out that JS is a dynamic language and it has no Strict Typing (even if Andr3a will surely argue).

Technically, it could be possible to simulate interfaces using JS - but this would violate the KISS principle, so I will use an alternative approach, that whilst being completely unrelated to interfaces, will let us work around this limitation.

This approach is called Duck typing, that can be summarized as:
<< If our class moves like a duck and has wings like a duck, then for us it's a duck (even if it is actually a pheasant) >>.

Another concept must be explained along with IOC: Dependency Injection,
which roughly says that an object "C" which knows neither objects "A" or "B" will be in charge of putting "the right B" inside "A".

"C" is also our container.


What exactly does a container do?
A container wraps a table uniquely identifying an object instance (usually components: tiny objects which do a single thing - but do it RIGHT), associating an unique identifier to it.

Yeah, right, cool stuff, but isn't it right about time to show some code?

Here's how we can easily manage a container:
var c={};
    //configuration of c
    c.B = { getMessage: function(){ return "test Container" } }
    
    //A doesn't know exactly B it only know that B have getMessage(duck typing approach)
    var A = {
        B: c.B, //A doesn't have the implementation of B,it rely on C to pass the correct one.
        test: function(){ alert(this.B.getMessage()) }
    }
    
    A.test();

Excuse me, but from what I understood so far, isn't "C" just a hashtable?

Well, no. Actually I'm introducing a concept at a time - in our implementation "C" is an hashtable, but to get a correct management of the IOC, this is not enough, a container must do more than that.

Depending on the configuration, a container must be able to instance the correct object (Factory). Here's where injection comes in: our container must be able to inject the object inside another object.

Each framework use different methodologies to inject dependencies. 

The two most common ways, which you will probably find in every framework, are injection by constructor and injection by setter. To keep things simple, my script depends from the extend script by Andrea Giammarchi, so make sure to include before your script.

var A ={
    test: function(){ alert(this.B.getMessage()) } //duck typing 
};

var container = {
    C : {},
     register:function (id,component){
       this.C[id]=component;
     },
     find: function (id){
       return this.C[id];
     },
     bySetter: function(){
       var id=arguments[0];
     
       var Obj = this.find(id);
       
       for(var i=1,max=arguments.length;i<max;i++  ){
         Obj = Obj.extend(arguments[i]);
     
       }

       return Obj;
     
    },
    byConstructor : function(){
  
      var id = arguments[0];
      var pars = new Array();
      for(var i=1,max=arguments.length;i<max;i++  )
       pars.push(arguments[i]);
  

      var Obj=this.find(id);
      return Obj.apply(Obj,pars);
 

   }

}

/*Start setter configuration*/
container.register('AS', A);

container.register('BS', {getMessage: function(){return 'Hello setter injection!'}});
container.register('BS2', {getMessage: function(){return 'Hello setter injection #2!'}});



container.bySetter('AS', {'B': container.find('BS')} ).test();
container.bySetter('AS', {'B': container.find('BS2')} ).test();


/*Constructor injection example*/
function AC(B){

  return {
    test:function(){alert(B.getMessage())}
  }
}

container.register('BC', { getMessage: function(){return 'Hello constructor injection '} });
container.register('AC', AC);


container.byConstructor('AC', container.find('BC')).test();



The reusable part of the script above is the container I wrote. It lets us register the components using register(id, component), as well as searching already registered components with find(id).
Last but not least, it lets you injecting by constructor with byConstructor(id, parameters) and injecting dependencies through a setter with bySetter(id, setterObject)


Finally, thanks to Andrea Giammarchi, you can find the code here: http://www.devpro.it/code/164.html

domenica, settembre 02, 2007

KentaIoC - A js IOC library


English version)



Ultimamente a lavoro sto usando un framework IOC

e fin da subito ho capito le potenzialità di un simile approccio, il quale permette
di separare concettualmente le proprie classi.
Per fare ciò ci si basa su un unico concetto, separare la logica che lega le classi esternamente.

Mentre nella programmazione tradizionale spesso accade che un oggetto A all' interno di un metodo configuri un oggetto B prima di invocare qualche metodo di ques'ultimo,
con l' Inversion of Control A non dovrà mai configurare B ma invocarlo direttamente.

probabilmente mi sono spiegato male e invito chi desiderasse capire meglio il concetto ad approfondire in maniera teorica l' argomento altrove in quanto ora mi concentrerò in maniera pragmatica nella scrittura di un codice che permetta l'utilizzo della IOC in javascript.



In che modo si mette in piedi l'IOC?
normalmente avremo una classe A che contiene al suo interno un membro B
che estende un interfaccia nota, in questo modo anche se A non conosce l'effettiva implementazione di B può dialogare con B poichè tra A e B c'è in piedi un contratto definito dall' interfaccia.
Si, ma in javascript non esiste il concetto di interfaccie, quindi la programmazione attraverso interfaccie non si può usare!
Ovviamente questo è il primo problema da affrontare, e a questo aggiungo che JS è un linguaggio dinamico e non ha lo Strict Type (non è un linguaggio fortemente tipizzato), anche se Andr3a sicuramente mi smentirà. volendo sarebbe possibile simulare le interfaccie in JS ma questo andrebbe contro il concetto KISS, quindi cercando un alternativa userò un concetto che nonostante non c'entri nulla con le interfaccie permette di lavorare lo stesso con questa metodologia.
Questo concetto che andrò a introdurre è il Duck typing,
ovvero se la nostra classe si muove come un fagiano e ha le ali di un fagiano allora per noi è un fagiano, anche se in realtà è un aquila.


Al pari con la IOC c'è un altro concetto, quello della Dependency Injection
che in pratica dice che un oggetto C che non conosce ne A ne B si occuperà di mettere "il giusto B" all' interno di A
C è inoltre il nostro Container.
Cosa fà esattamente un container?
Un container mantiene al suo interno una tabella che indica in maniera univoca un istanza di un oggetto(normalmente sono dei componenti, ovvero dei mini oggetti che fanno solo una cosa, ma la fanno bene) associandogli un identificativo.
Si, vabbè, ma non è ora di far vedere un po di codice?
Ecco come si può gestire facilmente un container.


var c={};
//configuration of c
c.B={getMessage:function(){return "test Container"}}

//A doesn't know exactly B it only know that B have getMessage(duck typing approach)
var A = {
B:c.B,//A doesn't have the implementation of B,it rely on C to have the correct one.
test:function(){alert(this.B.getMessage())}
}

A.test();

Ma da quel che ho capito C è solo un hashtable?
No, in realtà sto introducendo un concetto alla volta, se è vero che C è un hashtable
a tutti gli effetti, per avere una corretta gestione della IoC il container deve fare altro.
In base alla configurazione, il container deve poter istanziare il corretto oggetto (Factory)
ed è qui che entra in azione l'injection, il nostro container deve poter iniettare l'oggetto all' interno di un altro oggetto.
I vari framework hanno varie metodologie per iniettare le dipendenze, sicuramente le 2 più usate e che troverete in qualsiasi framework sono l'iniezione per costruttore e per setter.
per semplificare le cose il mio script dipende dall' extend script di andrea giammarchi
, assicuratevi quindi di includerlo in testa al vostro script

var A ={
test:function(){alert(this.B.getMessage())}//duck typing
};

var container = {
C : {},
register:function (id,component){
this.C[id]=component;
},
find: function (id){
return this.C[id];
},
bySetter: function(){
var id=arguments[0];

var Obj = this.find(id);

for(var i=1,max=arguments.length;i<max;i++ ){
Obj = Obj.extend(arguments[i]);

}

return Obj;

},
byConstructor : function(){

var id = arguments[0];
var pars = new Array();
for(var i=1,max=arguments.length;i<max;i++ )
pars.push(arguments[i]);


var Obj=this.find(id);
return Obj.apply(Obj,pars);


}

}

/*Start setter configuration*/
container.register('AS',A);

container.register('BS',{getMessage:function(){return 'Hello setter injection!'}});
container.register('BS2',{getMessage:function(){return 'Hello setter injection #2!'}});



container.bySetter('AS',{'B':container.find('BS')}).test();
container.bySetter('AS',{'B':container.find('BS2')}).test();


/*Constructor injection example*/
function AC(B){

return {
test:function(){alert(B.getMessage())}
}
}

container.register('BC',{getMessage:function(){return 'Hello constructor injection '}});
container.register('AC',AC);


container.byConstructor('AC',container.find('BC')).test();

La parte riutilizzabile dello script sopra è il container che ho scritto.
Il suddetto container permette di registrare i componenti usando register(id,component)
di cercare i componenti già registrati find(id)
permette infine di iniettare per costruttore byConstructor (id,parameters)
e di iniettare le dipendenze tramite setters bySetter(id,setterObject)


Grazie ad Andrea Giammarchi potete scaricare il codice da qui : http://www.devpro.it/code/164.html

domenica, aprile 29, 2007

Javascript ninja

recently i found this post in meeblog:
http://blog.meebo.com/?page_id=254

scrolling down to the end there is a simple test..

I think that that test is a bit confused, very vague... probably they do on purpose

now i gave the *REAL* (imho) answer to their question,
because i think that they are a good exercise ^_^;;
I hope doing so don't cause problems (I don't want enemy)


1. When does div.setAttribute(”###”) not equal div.###?

this question is vague... here some right answer(on angle brackets my suppposition):



always because ### is not a valid javascript

[if ### is a placeholder for a word]
since div is not defined if ### contains only character valid for a variable (i.e not -)
the error returned is always ("div is not defined");
so they are not equal when ### contains not valid javascript character for a object property.



[if they means DomNode.setAttribute]
since setAttribute want 2 parameter (name and value)
and since the value here is not showned then the first should raise a not enought argument error
the second one simply do nothing so they are always different.



2. What’s the difference between these two statements:

a. var x = 3;
b. x = 3;

[in global scope] there are no difference
[elsewhere] the first one create a private variable instead the second use (or create) a global variable.




3. What’s the difference between:

a. !!(obj1 && obj2)
b. (obj1 && obj2)

al 2 expression return always the same error:obj1 is not defined


[if we suppose that obj1 and obj2 are defined]

AND [if they are in using in a test (for example in a if condition)]
they are always the same since the condition automatically cast them as boolean value

[elsewhere] if they are in an assignment statement the difference is pretty simple

in the first case the returned value is true if both obj1 and obj2 are defined and not equals to false,undefined,null,0 or ''
ELSE the return value of this expression is false

in the second case if obj1 is equal to false,undefined,null,0 or '' the result is obj1 else is obj2


4. Write a one-line piece of JavaScript code that concatenates all strings passed into a function:

function concatenate(/*any number of strings*/) {

var string = /*your one line here*/
return string;
}



since in one line you could write all the code you want(separating with ; )


you could do something like

var string  = [''];(function(a){for(var i=0,max=a.length;i<max;i++)string[string.length]=a[i];})(arguments);string=string.join('');


5. What do these two examples have in common?

Example 1:

var obj = document.getElementById(’adiv’);
document.getElementById(’adiv’).ptr = obj;

Example 2:

function assignClick() {
var el = document.createElement(’div’);

function handleClick() {
el.innerHTML = ‘clicked!’;
}

el.attachEvent(”onclick”, handleClick);
}


both do nothing,
notice that the first could gave an error if there is not an element in the dom with the name adiv or if the node exists but the function is called before the dom is totally parsed (before oncontentload),
the second give an error if executed in an
application/xhtml +xml if the browser is not firefox since innerHTML
should don't exist(firefox is weird here)

giovedì, novembre 09, 2006

latest version of getXDOC don't work in IE 4 because in IE 4
try catch are not supported, but IE4 also know the CC
so we need a check for this..
and how can we make try catch invisible to IE4?
using a 'simple' eval
IE4 still don't work well, but is the better I can do ^_^;;

Also notice that the correct object for a XHR is
Msxml2.XMLHTTP, not DOMDocument!

getXDOC modified version:


function getXDOC(){
if(typeof(window.XMLHttpRequest)!='undefined')
return new XMLHttpRequest();

/*@cc_on

if(!(@_jscript_version<4)){
return eval('(function(){try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}catch(e__x){return new ActiveXObject("Msxml2.XMLHTTP.3.0");}}())');
}
@*/
return new ActiveXObject('Msxml2.XMLHTTP.3.0');

}



Sorry Andrea, I use conditional compilation again -.-

giovedì, novembre 02, 2006

Final method to obtain a dom Document ?

after the reading of this post on IE Blog talking about using the right version of msxml I come of a possible solution to get the XMLHttpRequest:

function getXDOC(){
//W3C native Object
if (window.XMLHttpRequest)return new XMLHttpRequest();

//IE 4.0 fallback [try..catch]
var progIDs=[];
progIDs[0]='Msxml2.XMLHTTP.3.0';
var i = 0;
/*@cc_on
progIDs = [ 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.3.0']; //6.0 is better of 3.0
for (; i < progIDs.length; i++) {
try{
@*/
if (window.ActiveXObject){
var xmlDOM = new ActiveXObject(progIDs[i]);
xmlDOM.setProperty("SelectionLanguage", "XPath");//because 3.0 default is XSLPattern
return xmlDOM;
}
/*@cc_on
}
catch (ex) {
}
}
@*/
return null;
}


Enjoy ;)

Ps. stay tuned for a corrected version..
Update:
http://mykenta.blogspot.com/2006/11/latest-version-of-getxdoc-dont-work-in.html

martedì, ottobre 10, 2006

Observer Subscriber in Base

I was playing with Dean Edwards Base and I would to implement
the Observer Subscriver pattern.
I wrote this Observer implementation:


//Clone method
Base.prototype.clone=function(){return new Base(this);}

//Define the Observer class
var Observer= Base.extend({
subscribe:function (obj,evt){
//if(!this["on"+evt])this["on"+evt]=[];
if(typeof(this["on"+evt]) === "undefined")this["on"+evt]=[];
this["on"+evt].push(obj);
},
raise:function (evt){
var list=this["on"+evt];

if(list){
var max=list.length;
for(var i=0;i<max;i++)
//if(list[i].update)list[i].update();
if(typeof(list[i].update)!=="undefined")list[i].update();
}
}
});
//Define the subscriber class
var Subscriber = Base.extend({update:function(){alert("update() must be implemented");}});


and this little test

/*Simple example of implementation*/

//Istantantiate a Observer
var observer= new Observer();

//Define a Event
observer.evt=function(){
//do stuff
this.raise("evt");
}

//Istantiate a Subscriber
var subscriber1=new Subscriber();
//Clone a Subscriber
var subscriber2=subscriber1.clone();

//define a custom update function
subscriber2.update=function(){
alert("here update() was implemented");
}

//subscribe our 2 object
observer.subscribe(subscriber1,"evt");
observer.subscribe(subscriber2,"evt");

//Raise the event
observer.evt();


Base is Great, it was so simple!




Update!
As I said in the comment this wasn't a correct implementation.

A correct(I hope) is the follow implementation:

//Clone method
Base.prototype.clone=function(){return new Base(this);}

var Observer = Base.extend({
update:function(evt){
alert("update() must be defined");
}
});
var Subject = Base.extend({
observers:[],
constructor:function(){this.observers=new Array();},
registerObserver:function(obj){
this.observers.push(obj);
return obj;
},
unregisterObserver:function(obj){
if(this.observers.length>0)
var tmp=this.observers.pop();
if (tmp!==obj){
var max=this.observers.length;
for(var i=0;i<max;i++)
if(this.observers[i]===obj){this.observers[i]=tmp;break;}
}
return this;
},
notifyObserver:function(evt){
var max=this.observers.length;
for(var i=0;i<max;i++)
this.observers[i].update(evt);
}
});

And so the Test:

/*Example:*/
var subject = new Subject();
subject.x=0;
subject.add=function(){
this.x++;
this.notifyObserver();
}
var observer1 = new Observer();
var observer2 =observer1.clone();
observer1.update=function(){alert("now x is "+subject.x);}
observer2.update=function(){alert("something happened on subject")}

subject.registerObserver(observer1);
subject.registerObserver(observer2);
subject.add();
subject.unregisterObserver(observer2);
subject.add();

venerdì, ottobre 06, 2006

typeof and Typeof

Dean Edwards point me out that typeof doesn’t always work so I come to a solution to this issue.

function isFunction(x){
return
typeof(x)==="function" &&
(typeof(x.toSource)==="undefined" || x.toSource().charAt(0)!="/")

}

basically it control if is a function (typeof(x)==="function")
and if is a gecko browser (typeof(x.toSource)==="undefined")
it control if is a RegExp(x.toSource().charAt(0)!="/").

So I wrote my simple Typeof function

function Typeof(what){
switch(what){
case Object:return "Object";
case Function:return "Function";
case Array:return "Array";
case String:return "String";
case Boolean:return "Boolean";
case Number:return "Number";
case RegExp:return "RegExp";
case Date:return "Date";
case Error:return "Error";
case Math:return "object";
case null:return "null";
}
if(typeof(what)==="function" && (typeof(what.toSource)!=="undefined" && what.toSource().charAt(0)=="/"))return "object"; //regex for moz
return typeof(what);
}


Enjoy ;)

venerdì, agosto 25, 2006

kentaromiura fastest device (duff's device optimized)


function kentaromiuraFastestDevice(iterations) {

var testVal=iterations;
if(parseInt(iterations/8)){
var n=iterations%8;
do{
--testVal; //do stuff
--testVal; //do stuff
--testVal; //do stuff
--testVal; //do stuff
--testVal; //do stuff
--testVal; //do stuff
--testVal; //do stuff
--testVal; //do stuff
}while(testVal!=n);
}
while(testVal--){
//do stuff
}
}

giovedì, luglio 20, 2006

standardise IE setAttribute (Part 2)

I go back to this subject because I've done some improvements to
the custom comment script that should Standardise IE 5.x setAttribute,
I create no other Object that could collide, look:


document.createElement = function(cE,interface){
//this is for DOM node not dinamically created
onload=function(){
var list=document.all;
var max=list.length;

while(--max)
{
list[max].getAttribute=interface.getAttribute;
list[max].setAttribute=interface.setAttribute;

}
//HTML node
list[0].getAttribute=interface.getAttribute;
list[0].setAttribute=interface.setAttribute;
}


return function (tagName) {
var element = cE(tagName);
element.getAttribute=interface.getAttribute;
element.setAttribute=interface.setAttribute;

return element;
}
}(document.createElement,{

getAttribute:function (attribute) {

switch(attribute){
case "class": attribute = "className";break;
case "for": attribute = "htmlFor";break;
case "style": return this.style.cssText;break;
case "type":return(this.id)?((document.getElementById)?document.getElementById(this.id):document.all[this.id]).type:this.type;break;
case "accesskey":return this.accessKey;break;
case "maxlength":return this.maxLength;break;
}
return this[attribute];
}

,setAttribute:function (attribute, value) {

switch(attribute){
case "name":return document.createElement(this.outerHTML.replace(/name=[a-zA-Z]+/," ").replace(">"," name="+value+">"));
case "class": attribute = "className";break;
case "for": attribute = "htmlFor";break;
case "type":
var me=this.parentNode;

if(!/id=/.test(this.outerHTML))
this.id=this.uniqueID;
if(me){
this.outerHTML=this.outerHTML.replace(/type=[a-zA-Z]+/," ").replace(">"," type="+value+">");




var t=me.childNodes;
var max=t.length;
for(var i=0;i<max;i++)
if(t[i].id==this.id){
t[i].getAttribute=this.getAttribute;
t[i].setAttribute=this.setAttribute;
}
}else this.type=value;

return;break;
case "accesskey":this.accessKey=value;return;break;
case "style": this.style.cssText =value;return;break;
case "maxlength":this.maxLength=value;return;break;
}

if(attribute.indexOf("on")==0){


this[attribute] = function(){eval(value)};

}
else
this[attribute] = value;
}
});


to use it just insert this line of code:

<!--[if lt IE 7]><script language="javascript" type="text/javascript" src="IEDOM.js"></script><![endif]-->

where IEDOM.js is the name of the script ..
Enjoy!


P.s. Look at http://www.devpro.it/JSL/ for a Great Library (
I would make a post for who don't want to Prototypize Object but won't use this great library!!
)

Update:
there are two known issues with this library:
first, if you use innerHTML instead of createElement you don't have the standard setAttribute,
so the solution is getting the node you are adding and extending the methods to each node it has

the second issue is the setAttribute("name") not updating dom. You was forced to return the correct node with setAttribute, so

var t=document.getElementById("x");
var n=t.setAttribute("name","usrname");
if(n)t=n;

now t is correct ;)

martedì, luglio 11, 2006

Another Pearl in the Javascript World

He Done It!


After my IE setAttribute solution (get here the complete solution along with my framework)


Andrea Giammarchi wrote a solution for the replace method, now you can use replace with a function as parameter, and is Standard ECMA compatible!


Try it or Get It!


It works on IE 5.x+, FF, NN,Opera, Safari, Konqueror ,


currently I haven't the complete compatibility list because is in a test state.


Now Javascript world is more standard!!! ;)


Example:


ECMA define that the function get the follow parameters


a)the Match of Regex passed as 1st argument


b)the N submatch (also known as parenthetical matches) with 0<N<99


c)position of the match in the original string


d)the original string


so "a12b34".replace(/[0-9][0-9]/g,function(a,b,c){return (Number(a)+1);}) must return "a13b35" in all the browser ;)

giovedì, maggio 11, 2006

addEvent

//Cannot be detached

function addEvent(obj,type,fn){
/*@cc_on obj.attachEvent('on'+type,function(){fn.apply(obj)});if(0){ @*/
obj.addEventListener( type, fn, false );
/*@cc_on } @*/
}

venerdì, maggio 05, 2006

getElementByClass

this code is now obsolete, take a look at this one to a better one, thanks.


document.getElementsByClassName = function(searchClass,node,tag)
{

if(node == null)node=document;
var ce = new Array();
if(tag==null || tag=='*')tag='*';
var els = new Array();
if (tag=='*' &&amp; document.evaluate){
var xpr=document.evaluate("//*",document, null, 0, null);
var t=true;
while (t=xpr.iterateNext()){
if(els.push)
els.push(t);
else
els[els.length]=t;
};
}
else
els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
var i;var j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) )
if (ce.push)
ce.push(els[i]);
else
ce[j++] = els[i];
}

return ce;

}