[ 3 posts ]

Yui Learner

  • Username: vo4yui
  • Joined: Sat May 05, 2012 3:21 pm
  • Posts: 2
  • Offline
  • Profile

Event Propagation

Post Posted: Tue Jul 17, 2012 8:31 am
+0-
Could someone try clicking on DIV2 multiple times. Why only first click affects DIV2. Am I doing it wrong. Thanks.
^^^^^^^^^^^^^^^^^^^^^^^^^^
<div id="div1">
DIV 1
<div id="div2">
DIV 2
</div>
</div>
<script>
YUI().use('node', function (Y) {
Y.one('#div1').on('click', function (ev) {
Y.log('==-IN div1');
Y.one('#div1').setHTML(addStars(Y.one('#div1')));
});
Y.one('#div2').on('click', function (ev) {
Y.log('==-IN div2');
Y.one('#div2').setHTML(addStars(Y.one('#div2')));
});
function addStars(node1){
Y.log('==-IN addStars');
return '***' + node1.getHTML();
}
});
</script>
^^^^^^^^^^^^^^^^^^^^^^^^^^

Juan Ignacio Dopazo

YUI Contributor

  • Username: jdopazo
  • Joined: Fri Oct 02, 2009 5:39 am
  • Posts: 618
  • Location: Buenos Aires, Argentina
  • Twitter: juandopazo
  • GitHub: juandopazo
  • Gists: juandopazo
  • Offline
  • Profile
Tags:

Re: Event Propagation

Post Posted: Tue Jul 17, 2012 10:34 am
+0-
Sorry, I misread your question originally.

I think the reason why it only affects DIV2 once is that the order of execution is:
- the event listener for DIV2 is fired
- the html of DIV2 changes
- the event listener for DIV1 is fired
- the html for DIV1 changes, this creates a new DIV2 DOM node with the same ID, but the first one is lost
- the second time it's clicked, only the DIV1 listener is fired

Luke Smith

YUI Contributor

  • Username: lsmith
  • Joined: Thu Aug 28, 2008 7:50 am
  • Posts: 507
  • Location: Sunnyvale
  • Twitter: ls_n
  • GitHub: lsmith
  • Gists: lsmith
  • IRC: ls_n
  • YUI Developer
  • Offline
  • Profile

Re: Event Propagation

Post Posted: Tue Jul 17, 2012 9:51 pm
+0-
Juan is right. Y.one('#div2') resolves to the DOM element with that id at that very moment. When you set innerHTML (as setHTML does) on an element, that portion of the DOM tree is replaced with new elements parsed from the html string. When #div1's setHTML() is called, the #div2 element that you subscribed from is gone, and all event subscriptions with it.

Event subscriptions execute from the deepest nested element to the outermost containing DOM node (exception being capture mode, which on() doesn't use). So #div2's subscription will execute first, then #div1's.

To avoid removing event subscriptions when element content is replaced, use event delegation. http://yuilibrary.com/yui/docs/event/delegation.html

HTH
  [ 3 posts ]
Display posts from previous:  Sort by  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum