sap.ui.require in SAP UI5 and require in nodejs

UI5
例如我需要在 controller 的 onShowHello 里通过 MessageToast 弹一个消息显示在 UI 上,

我需要先定义我自己的 controller,该 controller extend 自 UI5 标准的 controller module,路径为 sap/ui/core/mvc/Controller, 而为了调用 MessageToast 的 show 方法,也必须先拿到 MessageToast 的实例。所以 UI5 里使用 sap.ui.define 去加载这两个依赖的 module,加载完成后,会调用应用开发人员传入的回调函数,加载的两个 module 的内容作为两个输入参数传入该回调函数。

UI5 所有的 module 由 jquery.sap.global.js 中的 Module 统一管理。


更多细节请查看我的 SAP 前同事 Wu Ji 的博客SAPUI5 walkthrough step 6 – modules, dive in – how does modules work?
当然也存在 sap.ui.require 这种简洁用法。一个 UI5 框架的使用例子:

nodejs
逻辑和 UI5 类似,假设我想使用 queryString 这个 module,只需要用 nodejs 标准的 require 函数将其引入:

然后就可在应用代码里使用该 module 通过 module.exports 暴露出的方法:

require 调用 internal/module.js 里的 self.require:

然后是 Module._load:

nodejs 也有类似 UI5 的 module 统一管理器:Module._cache. 每次加载 module 时,首先从这个管理器里查看是否该 module 已经加载。只有当 module 在管理器里不存在时才会真正加载,new 一个 Module 对象,维护好属性后存入 module 管理器。

加载好的 module 就是一系列 function 的集合:

要获取更多 Jerry 的原创技术文章,请关注公众号"汪子熙":

版权声明: 本文为 InfoQ 作者【Jerry Wang】的原创文章。
原文链接:【http://xie.infoq.cn/article/07ce4f194fa91f064252e4e8e】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
评论