LimeJS指南4

來源:互聯網
上載者:User

標籤:io   color   ar   os   使用   java   sp   for   on   

# Events

在Lime中,事件的處理與Closure程式庫中的差不多,你可以用‘goog.events.listen(src,
type, listener, opt_capt, opt_handler)’添加事件監聽,用‘goog.events.unlisten
(src, type, listener, opt_capt, opt_handler)’取消監聽,目標對象(src)就是你經
常用的node元素。事件類型(tpye)是就是你一般情況下添加到你的DOM元素上的東西:通
常有*mousedown*, *mousemove* 和*mouseup*的滑鼠事件,還有*touchstart*,
*touchmove*,,*touchend*和*touchcancel*的touch事件。事件類型可以列為一個數列。

Lime事件處理背後的用意就是允許你將所有代碼為支援滑鼠事件和touch事件的裝置唯寫一
次。如果你以前已經嘗試過,你會發現這不像聽起來那麼容易。首先,滑鼠事件和touch事
件沒有一對一的關係。mousedown一般與touchstart一樣,而mousemove與touchmove完全不
同。其次,不同事件類型有執行方面的不同 - 不同事件的位置對於不同事件是不同的。再
者,touch裝置一般支援多觸控,這意味著你不能使用針對個別事件的處理者(handler),
但是你需要為個別互動設定下一個回答者(responder)。Lime嘗試解決所有這些問題。

在Lime中,當你為一個元素添加事件監聽時,事件對象不是普通的瀏覽器事件,而是
*lime.events.Event*的一個例子。這個對象的屬性包括

* *position* - Coordinate for the event in target node‘s coordinate space
* *screenPosition* - Coordinate for the event in screen coordinate space
* *targetObject* - Object that fired the event
* *event* - Normal browser event(you can call stopPropagation() on that for
example)

這些位置對於滑鼠和touch事件是一樣的。通過node對象的幫手函數,所有座標能被轉換成
不同座標。

## event.swallow()

事件對象也有‘swallow(eventType,handler)’方法,這允許你在多個事件中進行互動,你
使用它之後,你監聽第一個互動(mousdown,touchstart等),然後可以吞噬(swallow)
下一個mousemove或mouseup的事件。swallow意味著handler只會在它仍然是互動的一部分時
被調用。在一個多觸控的裝置每一個單獨的觸摸有自己的swallow handler,所以如果通過
一隻手指你的touchstart事件開始時,這不會與其他時刻的其他手指混淆。當互動結束時(
touchend, mouseup)所有swallowd listener將自動清除。

#!JavaScript
goog.events.listen(ball,[‘mousedown‘,‘touchstart‘],function(e){
this.setFill(‘#c00‘); // ball is colored to red when touched

e.swallow([‘mouseup‘,‘touchend‘,‘touchcancel‘],function(){
this.setFill(‘#0c0‘); // ball is colored back to green when
interaction ends
}
});

## Dragging

一個普通的互動就是拖動一個元素。Lime已經將它簡化。在事件‘event.startDrag()’,
你也可以提供參數以限制可拖動的範圍,返回到中心或者提供特定的對象。因為drag方法采
用與‘swallow()’相同的邏輯,每一個拖動是分開的,所以你可以同時拖動多個物體而不
寫一行代碼。

#!JavaScript
goog.events.listen(ball,[‘mousedown‘,‘touchstart‘],function(e){
e.startDrag(true); // true is for snapToCenter
});

## 非DOM元素

當你使用Canvas渲染時,沒有DOM元素承載事件。當開發未經加工的Canvas方法時這可能成
為問題,因為你只有一個事件目標。幸運的是在Lime中使用不同的渲染不會影響事件系統。
你仍可以在沒有DOM對等物的node上監聽事件。

## The Hit Test

如果你有一些古怪的自訂顯示對象,你可以重載它的‘hitTest()’方法以給它一個自訂的地區,它可以從這裡回應事件。預設所有sprite回應它們的邊界盒子(對於填充無效)。自訂形狀核對它們自己的幾何。層不具有任何身體,所以它們回應所有它們的子項目。

LimeJS指南4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.