开发者

onClick Vs Observer

开发者 https://www.devze.com 2023-02-14 15:44 出处:网络
I would like to know why it\'s better to use observe开发者_Python百科rs rather than adding the action directly into the onclick=\"\".

I would like to know why it's better to use observe开发者_Python百科rs rather than adding the action directly into the onclick="".

eg.

$('mybutton').observe('click', respondToClick);

vs

<a href="#" onclic="respondToClick()">button</a>

Thanks


This is a fairly common question so I'll refer you to a quality article on quirksmode.org that answers this question and other question you may have about event handling.

Here is an excerpt:

<a href="somewhere.html" onclick="alert('I\'ve been clicked!')">

It is very important to realize that this ancient way of event handling was de facto standardized by Netscape. All other browsers, including Explorer, had to conform to the way Netscape 2 and 3 handled events if they wanted JavaScript to work. Therefore these ancient events and event handlers work in all JavaScript browsers.

Have fun reading.


Generally most people would suggest to keep your javascript seperate from your html, allowing for faster html page rendering. You'll have to be more careful with the first though, due to cross browser incompatabilities with code


The biggest reason is that observe lets you register and unregister multiple observers via your JavaScript code, whereas assigning to onclick is a lot less flexible.


The three main reasons for me are as such:

  1. I like to keep my HTML templates abstract. Having javascript code embedded in the markup means my code re-use for that template code be slightly hampered. You would need to be sure you can include the script file in the head of the document. (For certain CMS systems, this can be a bit of a hassle to configure)
  2. How would you remove that event handler? el.onclick = null; won't always work. IE has a way of allowing memory leaks.
  3. Applying behaviors via class names or id's provides much greater re-usability for your javascript code than sticking in an onclick handler.
0

精彩评论

暂无评论...
验证码 换一张
取 消