Javascript Prototype Best Practice Event Handlers

Posted by nahum on Stack Overflow See other posts from Stack Overflow or by nahum
Published on 2010-05-08T17:00:35Z Indexed on 2010/05/08 17:08 UTC
Read the original article Hit count: 218

Hi this question is more a consulting of best practice, Sometimes when I'm building a complete ajax application I usually add elements dynamically for example. When you'r adding a list of items, I do something like:

var template = new Template("<li id='list#{id}'>#{value}</li>");
var arrayTemplate = [];
arrayOfItem.each(function(item, index){
   arrayTemplate.push(template.evaluate( id : index, value : item))
});

after this two options add the list via "update" or "insert"

----- $("elementToUpdate").update("<ul>" + arrayTemplate.join("") + "</ul">);

the question is

how can I add the event handler without repeat the process of read the array, this is because if you try add a Event before the update or insert you will get an Error because the element isn't still on the DOM.

so what I'm doing by now is after insert or update:

arrayOfItem.each(function(item, index){
   $("list" + index).observe("click", function(){
     alert("I see the world");
   })
});

so the question is exist a better way to doing this??????

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about event-handling