每個 JavaScript 框架都會把跨瀏覽器的事件處理包一層,鼓勵你告別老式的行內事件,改用乾淨的線性寫法。以下用 jQuery 與 Prototype 對照,看同一件事在不同框架裡長什麼樣子。
清單 6 使用 jQuery 附加 hover 事件
$('#the-box').hover(function() {
$(this).addClass('highlight');
}, function() {
$(this).removeClass('highlight');
});
hover 是 jQuery 的特殊事件,它接受兩個函數:第一個在 mouseover 時執行,第二個在 mouseout 時執行——因為 DOM 標準裡並沒有 hover 這個原生事件。
更典型的事件寫法像 click 這樣,只收一個函數:
清單 7 使用 jQuery 附加 click 事件
$('#the-button').click(function() {
alert('You pushed the button!');
});
jQuery 裡大多數事件都是這個模式,而且事件處理函數中的上下文(this)就是觸發事件的那個物件。
有些框架的做法不同。以 Prototype 為例,同樣的功能會寫成:
清單 8 使用 Prototype 附加 click 事件
$('the-button').observe('click', function(e) {
alert('You pushed the button!');
});
有兩點值得注意:沒有 click 這種專用函數,而是統一的 observe,事件名稱當作參數傳入;再者,回呼會收到一個事件物件 e,要取得觸發事件的元素得自己向它要。
於是用 Prototype 重寫 hover,就得把 mouseover 與 mouseout 分開綁:
清單 9 使用 Prototype 附加懸停事件
$('the-box').observe('mouseover', function(e) {
var el = Event.element(e);
el.addClassName('highlight');
});
$('the-box').observe('mouseout', function(e) {
var el = Event.element(e);
el.removeClassName('highlight');
});
jQuery 只要用 $ 就能拿到上下文,Prototype 則得呼叫 Event.element(e)。
前面的範例都把函數寫成匿名函數,這意味著它無法重複使用。既然 mouseover 與 mouseout 本來就要綁同一件事,不如抽成具名函數:
清單 10 使用 Prototype 改進懸停事件
function toggleClass(e) {
var el = Event.element(e);
if(el.hasClassName('highlight'))
el.removeClassName('highlight');
else
el.addClassName('highlight');
}
$('the-box').observe('mouseover', toggleClass);
$('the-box').observe('mouseout', toggleClass);
這時只需要定義一個函數,同時交給兩個事件使用;函式會依元素目前有沒有 highlight 這個 class 來決定要加還是要移除。另外注意 e 是隱式傳入的——你把 toggleClass 交給 observe,並沒有明確傳任何參數,事件物件會由框架自動送進來。這個小細節,正是許多人從匿名回呼改寫成具名函數時最容易卡住的地方。