Weex iOS源码解析(一):Handler机制

本文基于Weex 0.18.0版本源码

一、设计思想

Weex的Handler是一种插件化设计思想,App通过注册Handler到WXHandlerFactory扩展Weex的功能,比如图片的下载,Weex性能数据的监听。

二、调用方法

WXSDKEngine类

+ (void)registerHandler:(id)handler withProtocol:(Protocol*)protocol; 注册Handler,该Hander实现了协议protocol

+ (id)handlerForProtocol:(Protocol*)protocol;获取protocol对应的Handler对象

上述两方法的调用实际上最后会路由到WXHandlerFactory,WXHandlerFactory实现了Handler的注册和查询,该类是个全局单例,通过一个线程安全的字典来存储protocol->handler的映射,如下所示。

三、示例

目前Weex实现了三种默认的Handler

+ (void)_registerDefaultHandlers {    

[self registerHandler:[WXResourceRequestHandlerDefaultImpl new] withProtocol:@protocol(WXResourceRequestHandler)];  

 [self registerHandler:[WXNavigationDefaultImpl new] withProtocol:@protocol(WXNavigationProtocol)];    

 [self registerHandler:[WXURLRewriteDefaultImpl new] withProtocol:@protocol(WXURLRewriteProtocol)];     

}

WXResourceRequestHandlerDefaultImpl 实现了网络请求的发送与接受;WXNavigationDefaultImpl是在navigation Module 中调用 push 和 pop 的一些操作时候被调用,WXURLRewriteDefaultImpl实现了url的重写,可以将特定的 URL,重写为本地 URL 或者其他路径。

目前可以实现的Protocol协议在Protocol目录下,App必须要实现图片下载协议WXImageOperationProtocol。

一些其他常用的协议介绍如下:

WXConfigCenterProtocol:key-value的配置中心,通过该协议实现一些默认的配置;

WXAppMonitorProtocol:App性能数据监控协议,通过该协议可以拿到weex加载时间等一些性能时间;

WXJSExceptionProtocol:JS异常,通过实现该协议,可以监控JS的异常;

WXEventModuleProtocol:通过实现该协议方法openUrl,weex页面可以跳转到nativc 页面;

你可能感兴趣的:(Weex iOS源码解析(一):Handler机制)