Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!eternal-september.org!feeder.eternal-september.org!aioe.org!.POSTED!not-for-mail From: Cezary Tomczyk Newsgroups: comp.lang.javascript Subject: Re: Clone node with events Date: Sat, 12 Jan 2013 23:00:46 +0100 Organization: Aioe.org NNTP Server Lines: 38 Message-ID: References: NNTP-Posting-Host: zYd0PXwpR9QMvAmoEDGsiw.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20130107 Thunderbird/17.0.2 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.javascript:18095 W dniu 2013-01-10 17:15, Stefan Weiss pisze: > On 2013-01-10 12:33, Cezary Tomczyk wrote: >> Any idea how to in an efficient and proper way clone node with events? > > That doesn't seem like a good idea in the first place (for the reason > Scott mentioned), but maybe there's a better way. When you have a number > of elements that should react in a similar way to an event, consider > using event delegation instead of separate listeners for each element. Yes, I know event delegation. They are powerful :-) > Simply put, that means attaching one listener to a common parent > element, and resolving the event target from there. This works > especially well for click events; other event types (like mouseover, > mouseout) can be a little more tricky. Some events do not bubble at all > (focus, blur, change, etc). > > If you can't use event delegation, use a wrapper function to > create/clone the element and attach the listeners at the same time: > > function handleFocus (evt) {} > > function makeInput (node) { > var input = node ? node.cloneNode() > : document.createElement("input"); > input.addEventListener("focus", handleFocus); > return input; > } That is the only way, as I see, at this moment. But this is useful when you know what type of events are attached. Otherwise, as I mentioned in reply to Scott, it is better to write some wrapper to event methods and use collected data (I mean attached events) to attach them again after replacing element. -- Cezary Tomczyk http://www.ctomczyk.pl/