0

I'm new to YUI. Can some tell me why should I use only second method?

Y.all('div span').on('mouseover',mOver); Y.one('div').delegate('mouseover',mOver,'span');

Mixcels
  • 889
  • 1
  • 11
  • 23
Ajay Gangisetti
  • 431
  • 2
  • 5
  • 13

1 Answers1

1

The first attaches a separate event listener to every single div span element. If there's a lot of elements, then you are creating a lot of events, more memory used etc. Even if you were doing this, you probably mean on instead of delegate - as you've written this, I don't think the two statements are equivalent.

As you've written it, though, the first approach adds a delegated event listener to every div span - so it will catch events bubbling up from child elements of the span.

The second attaches a single event listener to the parent div element. Any event on a child span element will bubble up* through the DOM and get caught by the event listener.

You shouldn't only use the second method. There may be legitimate reasons to use the first method. However, in many cases (in my experience at least), event delegation is to be preferred as it is more efficient and easier to manage.

(*) You might want to read this What is event bubbling and capturing? about event bubbling. Events bubble up through the DOM unless they are stopped (halt()ed in YUI) by an event listener lower down the DOM.

Also, in case you are now aware, YUI has been end-of-lifed by Yahoo and as far as I know will not be maintained by anyone in the future (http://yahooeng.tumblr.com/post/96098168666/important-announcement-regarding-yui)

Community
  • 1
  • 1
Matt Parker
  • 284
  • 1
  • 3