在AS3中最容易实现onReleaseOutside?

dav*_*avr 4 migration flash actionscript-2 actionscript-3

我是一个长期的ActionScript 2用户,现在开始使用ActionScript 3.我缺少的一件事是复制AS2的MovieClip.onReleaseOutside功能的简单方法.几乎总是有必要实现这个事件,否则你会得到一些有趣的错误,比如flash认为你的鼠标已经关闭了.

根据AS2到AS3迁移指南,我应该使用flash.display.InteractiveObject.setCapture()它,但据我所知,它不存在.我猜这个文件已经过时或不正确.我在网上发现了一些关于如何复制这个功能的帖子,但是他们有自己的问题:

  • 即使没有相应的onPress事件,这个触发onReleaseOutside.
  • 这个效率似乎非常低效,每次在应用程序内的任何位置单击鼠标时,您都会添加和删除事件侦听器.

必须有一个更简单的方法,不要告诉我Adobe在重写Actionscript时忘了这个吗?

示例AS2代码:

// Assume myMC is a simple square or something on the stage

myMC.onPress = function() {
  this._rotation = 45;
}

myMC.onRelease = myMC.onReleaseOutside = function() {
  this._rotation = 0;
}
Run Code Online (Sandbox Code Playgroud)

没有onReleaseOutside处理程序,如果你按下squre,将鼠标拖到它外面,然后释放鼠标,那么方块就不会旋转,并且看起来被卡住了.

Ant*_*tti 10

简单而万无一失:

button.addEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );
button.addEventListener( MouseEvent.MOUSE_UP, buttonMouseUpHandler ); // *

function mouseDownHandler( event : MouseEvent ) : void {
    trace( "onPress" );
    // this will catch the event anywhere
    event.target.stage.addEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );
}

function buttonMouseUpHandler( event : MouseEvent ) : void {
    trace( "onRelease" );
    // don't bubble up, which would trigger the mouse up on the stage
    event.stopImmediatePropagation( );
}

function mouseUpHandler( event : MouseEvent ) : void {
    trace( "onReleaseOutside" );
    event.target.removeEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );
}
Run Code Online (Sandbox Code Playgroud)

如果您不关心onRelease和onReleaseOutside之间的区别(例如可拖动项目),您可以跳过按钮本身的鼠标向上监听器(此处用星号表示).