How to Use Custom Events in Corona
How to Use Custom Events in Corona
1년 쯤 전에 (2011년 6월), Corona Event Model 에 대해서 다뤘었습니다. 거기서 코로나에서의 이벤트가 정확히 무엇인지 설명을 했었죠. 이벤트가 발생했을 때 어떻게 여러분이 hook 해서 코로나의 여러 기능들을 적용할수 있는지에 대해서도 다뤘었습니다.
하여간 지난번에는 코로나에서 제공하는 built-in 이벤트들에 대해서 그 API를 주로 다뤘었습니다. 그 때 제가 다루지 않았던 부분은 개발자가 스스로 custom 이벤트를 정의할 수 있다는 것입니다. 그리고 그 이벤트가 발생했을 때 listen 할 수 있다는 것하구요.(개발자 스스로 완벽하게 컨트롤 할 수가 있죠)
이 튜토리얼은 여러분만의 custom 이벤트를 어떻게 정의하고 dispatch 하는지에 대해 알려드릴겁니다. 여러분은 여러분의 게임이나 앱에 이 기능들을 적용할 수 있겠죠. 만약 여러분이 코로나 이벤트 모델에 대해서 그렇게 친숙하지 않다면 우선 The Corona Event Model Explained부분을 읽고 난 후 아래 부분을 읽기를 권장합니다.
The Scenario
이 튜토리얼의 시나리오를 한번 짜 보면 한개의 object와 하나의 player 가 있습니다. 여기에 그 건강상태와 관련된 많은 이벤트를 적용해 볼 겁니다. 우리는 이것을 health 이벤트라고 부르겠습니다. (이름은 여러분이 원하는대로 붙이시면 됩니다. 단지 다른 Corona event와 이름이 중복되거나 이미 있는 다른 custom event와 이름이 겹치지만 않으면 되요.)
Dispatching an Event
게임이 시작되면 어떻게 되는지 한번 얘기해 봐요. player의 건강은 75%일 겁니다. 그는 med pack을 집을거고 그러면 그의 건강의 100%가 될겁니다. 이 부분에서 우리는 health 이벤트를 dispatch 할 겁니다. event.type을 full로 할거구요. 여기서 여러분이 첫 번째로 할 일은 event table을 만드는 겁니다. 이 테이블은 listener 함수에 보낼 모든 데이터를 가지고 있게 될 겁니다. 일단 event table 셋업이 완료 되면 여러분은 object:dispatchEvent() 메소드를 call 할 수 있습니다.
name = "health",
type = "full",
healthPercent = 100
}
player:dispatchEvent( event )
아래에 보면 health level이 low나 empty일 때 어떻게 health를 dispatch 하는지 보여 드립니다.
name = "health",
type = "low",
healthAmount = 10
}
player:dispatchEvent( event )
name = "health",
type = "empty",
healthAmount = 0
}
player:dispatchEvent( event )
Listening to Events
아래 예제는 player object가 dispatch 된 health 이벤트들에 어떻게 object listen 하게 되는지를 보여드리고 있습니다.
if event.type == "full" then
print( event.healthAmount ) -- 100
turn_health_bar_green()
elseif event.type == "low" then
print( event.healthAmount ) -- 10
warn_player()
turn_health_bar_red()
elseif event.type == "empty" then
print( event.healthAmount ) -- 0
initiate_game_over()
end
end
player:addEventListener( "health", health_listener )
table listener를 사용함으로서 self object로 그 object를 reference 할 수 있게 됩니다.
if event.type == "full" then
print( event.healthAmount ) -- 100
turn_health_bar_green()
elseif event.type == "low" then
print( event.healthAmount ) -- 10
warn_player()
turn_health_bar_red()
elseif event.type == "empty" then
print( event.healthAmount ) -- 0
initiate_game_over()
end
end
player.health = health_listener
player:addEventListener( "health", player )
Things to Keep in Mind
믿으실지 모르겠지만 custom event의 dispatch와 listening 을 모두 끝냈습니다. 이제 여러분이 custom event를 사용하실 일 만 남았는데요. 몇가지 염두에 두셔야 할 것을들 정리했습니다.- 코로나에 이미 내장된 코로나 이벤트와 비교해서 살펴보면 custom event에서는 이벤트가 dispatch 될 때 반드시 여러분이 컨트롤 해야 합니다.
- 코로나에 이미 내장된 코로나 이벤트와 마찬가지로 이벤트를 dispatch 되게 하기 위한 object listening을 하지 않으면 아무 일도 일어나지 않습니다.
- object:dispatchEvent() method에 pass 된 이벤트 테이블은 name 키가 필요합니다. 그 나머지는 옵션입니다.
이벤트를 사용하는것은 또한 간단한 코딩을 지원합니다. 그러므로 유지보수를 더 수월하게 하죠. 어떤 종류의 custom 방식으로 코로나의 이벤트 모델을 사용하실건가요?