因为是有关Mediator和Command的事件,所以将事件枚举命名为
public enum MCCubeEvent { UpdateCunePos, UpdateCunePosComplete }
先是Mediator层
using UnityEngine; using strange.extensions.mediation.impl; using strange.extensions.dispatcher.eventdispatcher.api; using strange.extensions.context.api; public class CubeViewMediator : EventMediator { [Inject] public CubeView cubeView{ get; set;} public override void OnRegister () { //监听Command处理完成的回调 dispatcher.AddListener(MCCubeEvent.UpdateCunePosComplete, OnUpdatePosComplete); cubeView.dispatcher.AddListener(VMCubeEvent.UpdatePosition, OnUpdatePos); } public override void OnRemove () { cubeView.dispatcher.RemoveListener(VMCubeEvent.UpdatePosition, OnUpdatePos); dispatcher.RemoveListener(MCCubeEvent.UpdateCunePosComplete, OnUpdatePosComplete); } private void OnUpdatePos(IEvent evt) { //发送命令给Commamd,事先会在Context下绑定,直接调用Command的Execute()方法 dispatcher.Dispatch(MCCubeEvent.UpdateCunePos,(int)evt.data); } private void OnUpdatePosComplete(IEvent evt) { cubeView.UpdatePosition((Vector3)evt.data); } }
然后是Command层
using UnityEngine; using strange.extensions.command.impl; public class CubeUpdateCommand : EventCommand { [Inject] public CubePositionModel DataModel { get; set; } public override void Execute() { Vector3 newPos = DataModel.pos; newPos.x += Random.Range(-2f, 2f); DataModel.pos = newPos; //处理完后,回调给Mediator,Mediator事先已经监听好了 dispatcher.Dispatch(MCCubeEvent.UpdateCunePosComplete,newPos); } }
下面是绑定
commandBinder.Bind(MCCubeEvent.UpdateCunePos).To<CubeUpdateCommand>();
总结:两者都是通过全局的dispatcher发送事件的。Mediator通过发送事先在绑定处绑定好了命令的事件来通知Command处理,Command通过发送Mediator层事先绑定好的回调事件来通知Mediator。