Показать сообщение отдельно
Старый 25.04.2010, 23:40
Nirth вне форума Посмотреть профиль Отправить личное сообщение для Nirth Посетить домашнюю страницу Nirth Найти все сообщения от Nirth
  № 5  
Ответить с цитированием
Nirth
4AM Games
 
Аватар для Nirth

блогер
Регистрация: Nov 2002
Адрес: Sofia
Сообщений: 6,264
Записей в блоге: 1
Отправить сообщение для Nirth с помощью ICQ Отправить сообщение для Nirth с помощью AIM Отправить сообщение для Nirth с помощью MSN Отправить сообщение для Nirth с помощью Yahoo Отправить сообщение для Nirth с помощью Skype™
Я обновил код на всякий случай:
Код AS3:
/*
The MIT License
 
Copyright (c) 2010 David Sergey, nirth@fouramgames.com, nirth.furzahad@gmail.com
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package kii.utils
{
	public function listen( closure:Function, ...rest:* ):void
	{
		var i:uint = 0;
		var l:uint = rest.length;
		var args:Array = [];
 
		if( rest[l - 3] is Boolean )
			args = rest.splice( -3, 3 );
		else if( rest[l - 2] is Boolean )
			args = rest.splice( -2, 2 );
		else if( rest[l - 1] is Boolean )
			args = rest.splice( -1, 1 );
 
		log( 'args:', args );
		if( closure.length == 3 && args.length > 1 )
			args = [args[0]];
 
		if( rest[0] is Function )
			var handler:Function = rest.shift();
 
		if( handler as Function )	//We assuming that all Events have one Handler
			for( i = 0; i < rest.length; i ++ )
				closure.apply( null, [ rest[i], handler ].concat( args ) );
		else						//Else we asume that arguments are passed in a way [event, handler, event, handler]
			for( i = 0; i < rest.length; i += 2 )
				closure.apply( null, [rest[i], rest[i + 1]].concat( args ) );
	}
}
Код AS3:
/*
The MIT License
 
Copyright (c) 2010 David Sergey, nirth@fouramgames.com, nirth.furzahad@gmail.com
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package kii.utils
{
	import flash.events.IEventDispatcher;
	/**
	 *
	 * @example	
	 * <code>
	 * 	var listen:Function = switcher( this, handle, FlexEvent.CREATION_COMPLETE, FlexEvent.PREINITIALIZE, FlexEvent.INITIALIZE );
			listen( true );		//Adds listener "handle" to CREATION_COMPLETE, PREINITIALIZE, INITIALIZE events
			listen( false );	//Removes them
			//Or
			var listen:Function = switcher( this, FlexEvent.CREATION_COMPLETE, handleCreationComplete,
												  FlexEvent.PREINITIALIZE, handlePreInitialize,
												  FlexEvent.INITIALIZE, handleInitialize,
												  false, 0, true ); //capture = false, priority = 0, weakReference = true
				listen( true );		//Adds handleCreationComplete => CREATION_COMPLETE, handlePreInitialize => PREINITIALIZE etc.
				listen( false );	//Removes them 
	 */
	public function switcher( dispatcher:IEventDispatcher, ...rest ):Function
	{
		return function( add:Boolean ):void
		{
			if( add )
				listen.apply( null, [dispatcher.addEventListener].concat( rest ) );
			else
				listen.apply( null, [dispatcher.removeEventListener].concat( rest ) );
		};
	}
}
listen принимает первым параметром removeEventListener или addEventListener (в зависимости от, того хочешь ли ты добавить или удалить события.
После первого параметра, можно передавать аргументы либо:
Функция, Событие, Событие, Событие ...
Либо
Событие, Функция, Событие, Функция ...

Первый вариант подписывает 1 хендлер, для всех событий. Второй делает индивидуальные хендлеры для сабытий.
[as3]listener( addEventListener, 'complete', myCompleteHandler, 'error', myErrorHandler' ); //подпишет myCompleteHandler( event:Event) под complete событие и тд.
listener( addEventListener, universalHandler, 'complete', 'error' ); //подпишет один хендлер под оба события.

Последний 1-3 параметра могут быть в формате Boolean | Boolean, Number | Boolean, Number, Boolean собственно это для bubbles, priority, weakReference параметров.

Функция свитчер, вместо метода, берет первым аргументром экземпляр IEventDispatcher, и возвращает метод, если аргумент true то будет использоватся IEventDispatcher.addEventListener, если false то IEventDispatcher.removeEventListener.

Вобщем это может выглядеть как функциональное вуду, но за 3 месяца работы со Скалой и две недели с Эрлангом с таким даже привычней работать, чем с чистым ООП ^_^.
__________________
Я перестал переписывать, начал редактировать, еще лет 15 и я стану писателем ^_^