开发者

Help me to understand basic priciples of Unobtrusive JavaScript

I found these basic principles of Unobtrusive JavaScript from Wikipeia/Unobtrusive_JavaScript:

  • Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
  • Best practices to avoid the problems of traditional JavaScript programming (such as br开发者_StackOverflow社区owser inconsistencies and lack of scalability)
  • Progressive enhancement to support user agents that may not support advanced JavaScript functionality

I can understand first one easily. I also can understand second one's avoid the problems of lack of scalability. I wonder how Unobtrusive JavaScript can help to avoid browser inconsistencies. On the contrary, sometimes Obtrusive way can help to avoid browser inconsistencies. For example, to add event to some element I should do this in Unobtrusive way:

<div id="button">Button</div>
<script>
var button = document.getElementById('button');

function buttonClick() {
  // do something
}

if (button.addEventListener) 
  button.addEventListener('click', buttonClick, false);
else
  button.attachEvent('onclick', buttonClick);
</script>

if I do it Obtrusive way:

<div id="button" onclick="buttonClick()">Button</div>
<script>
function buttonClick() {
  // do something
}
</script>

As you can see Obtrusive way is simpler and not needed to care about browser inconsistency. So could you explain or show me any examples how Unobtrusive way can help to avoid browser inconsistencies.

And third one. I can do progressive enhancement in Obtrusive way. For example, I can still use Modernizr in Obtrusive way.

How can Unobtrusive JavaScript help to do these?


Well, what you say is true, but there are some other HTML properties that are not that standard. for example stuff like

<input disabled>

or

<input disabled="disabled">

can be handled in unobtrusive javascript more consistently.


you can use HTML properties, like Arash say, but it's not W3c Valid. If you will pass the W3c validation, it's better to use Javascript


I generally prefer to use simple and precise polyfills. For your example, you could just include addEventListener polyfill (https://gist.github.com/eirikbacker/2864711) and then use a standard way :

<div id="button">Button</div>
<script type="text/javascript" src="./polyfills/addEventListener-polyfill.js"></script>
<script>
    var button = document.getElementById('button');

    function buttonClick() {
        // do something
    }

    button.addEventListener('click', buttonClick, false);
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜