Jerry最开始是用SAP UI5进行SAP CRM Fiori应用的开发。最近一段时间做SAP Spartacus开发,在用Angular,因此借这个机会将两个前端框架的事件处理实现细节做一个比较。
SAP UI5事件处理
通过button控件的attachPress方法注册一个Press事件点击的处理函数:

button控件本身的实现是没有attachPress这个方法的,这一点可以从hasOwnProperty返回false来确认:

Instead, it is provided by the node in the button instance’s prototype chain, EventProvider.
顺着SAP UI5 button原型链沿着继承关系向上寻找,最后发现在EventProvider里提供了attachEvent方法。如果对SAP UI5 button的原型链不熟悉,可以参考我这篇文章:深入学习SAP UI5框架代码系列之一:UI5 Module的懒加载机制

当我们应用代码里调用attachPress时,传入这个函数的事件响应函数被加入到一个SAP UI5统一维护的事件处理注册表mEventRegistry里,这是一个键值对数据结构,key为应用程序注册的事件名称,值为我们传入的 事件响应函数。如下图所示,key为press,值为fFunction:

当我们点击了UI上的按钮之后,SAP UI5控件的Button.onclick方法会被调用,里面会fire一个Press事件。这里完成了浏览器原生的click事件到语义事件Press的转换。

SAP UI5根据press,到事件注册表mEventRegistry里去查找,将所有注册到该事件上的所有响应函数取出,放到一个数组aEventListeners里,遍历这个数组,逐一调用响应函数。

Angularjs事件处理
下图是一个Angularjs应用,基于Angularks 1.2.18开发而成. 在界面上显示了硬编码之后的三个国家的人口,我希望通过人口对这三个国家进行排序。

我给Country这一列通过ng-click指令注册了一个排序逻辑:sortField = 'name'

Angular和SAP UI5一样,有自己的bootstrap阶段。在此阶段Angular框架做的事情之一,就是Angular框架会通过下图第964行代码即compile函数,遍历html DOM树。

如果发现有一个element attribute具有ng前缀,执行applyDirectivesToNode函数,为该节点添加一些特殊的逻辑。
Angular通过下列的三个步骤,对ng-click = "sortField = 'name'"进行响应函数注册:

第一步:解析包含ng-click= "sortField = 'name'"的HTML元素,创建一个wrapper fn.
第二步:15328行,使用element.on给click事件注册响应函数。这个响应函数内部调用Angular第一步创建的wrapper fn.
第三步,用户点击超链接之后,15330的函数触发。

“sortField = ‘name’” 通过assign函数实现:

Finally, scope obj ( you can consider scope as “Model” in UI5 at this moment ) has attribute sortField which has been assigned with a new value “name”, this is how
“sortField = ‘name’”的执行:Scope对象的属性sortField被赋上了值:name


更多Jerry的原创文章,尽在:"汪子熙":

网友评论