因为是View和Mediator的交互,所以我将事件枚举命名为
public enum VMCubeEvent { UpdatePosition, }
新建CubeView
using UnityEngine; using strange.extensions.mediation.impl; using strange.extensions.dispatcher.eventdispatcher.api; public class CubeView : View { [Inject]//使用局部的派发器 public IEventDispatcher dispatcher { get; set; } //提供接口 public void UpdatePosition(Vector3 pos){ this.transform.position = pos; } private void OnMouseDown() { //Cube被点击后,发送命令通知Mediator dispatcher.Dispatch(VMCubeEvent.UpdatePosition,Random.Range(1,10)); } }
对应的Mediator
using UnityEngine; using strange.extensions.mediation.impl; using strange.extensions.dispatcher.eventdispatcher.api; using strange.extensions.context.api; public class CubeViewMediator : EventMediator { [Inject]//注入View,直接调用View接口交互 public CubeView cubeView{ get; set;} public override void OnRegister () { //监听View层发出的命令 cubeView.dispatcher.AddListener(VMCubeEvent.UpdatePosition, OnUpdatePos); } public override void OnRemove () { cubeView.dispatcher.RemoveListener(VMCubeEvent.UpdatePosition, OnUpdatePos); } private void OnUpdatePos(IEvent evt) { //发送命令去Command层做逻辑计算等 //evt.data View传过来的数据 //当命令有回应时,直接调用View接口传递给View //cubeView.UpdatePosition((Vector3)evt.data); } }
总结:View用来和用户交互,感知事件的发生,然后通过局部的dispatcher派发命令通知Mediator层,Mediator事先通过这个局部的dispatcher监听好事件的回调,触发这个回调(处理),处理完成后,通过View引用直接访问提供好的接口更新交互。