無侵入性是近幾年相當盛行的JavaScript設計觀念,它主張JavaScript不應該對網頁原始碼以及使用者造成干擾。為了達成這個訴求,首要的目標就是讓HTML標記與JavaScript程式保持分離,讓內容與行為能清楚畫分為二,因此可以透過模組化的方式,使JavaScript不與HTML文件混雜在一起。同時,也要能確保如果不能執行JavaScript時,網頁一樣能正常運作。
舉個例子
<img id="myImg" src="11.jpg" onmouseover="this.src='22.jpg'" onmouseout="this.src='11.jpg'" />
可以改成
document.getElementById("myImg").onmouseover = function(){this.src="22.jpg"};
document.getElementById("myImg").onmouseout = function(){this.src="11.jpg"};
也就是把事件行為抽離html,使用 DOM 的事件委託方法來寫,html碼裡不再混雜 javascript 程式碼。
相關的設計原則可參考
The seven rules of Unobtrusive JavaScript
http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/
書籍參考
ppk on JavaScript 中文版
更多資訊
Yahoo! Design Pattern Library
http://developer.yahoo.com/ypatterns/
Event Delegation
http://icant.co.uk/sandbox/eventdelegation/
Event Driven JavaScript Application Design
http://yuiblog.com/blog/2007/01/17/event-plan/
JavaScript Programming Patterns
http://www.klauskomenda.com/code/javascript-programming-patterns/
Show love to the Object Literal
http://www.wait-till-i.com/2006/02/16/show-love-to-the-object-literal/
A JavaScript Module Pattern
http://yuiblog.com/blog/2007/06/12/module-pattern/
留言列表