PureMVC(JS版)源码解析(三):Observer类
上一篇博客中,我们讲到了Notification类(消息类),Notification(消息)是连接观察者(observer)和通知者(notifier)之间的桥梁。这一篇博客,主要是在代码层面上讲一下observer类。
通过源码,我们可以看出Observer类有两个属性,分别是notify和context,notify是函数类型,context是object类型,其中notify是Observer对象(观察者)接收到消息之后执行的回调函数,context是回调函数的执行作用域。
/** * The Observers callback Function * * @private * @type {Function} */ Observer.prototype.notify= null; /** * The Observers callback Object * @private * @type {Object} */ Observer.prototype.context= null;
这两个属性,分别有get/set方法。[setNotifyMethod()/getNotifyMethod()/setNotifyContext()/getNotifyContext()];
Observer在构造函数中对这两个属性进行了初始化:
function Observer (notifyMethod, notifyContext) { this.setNotifyMethod(notifyMethod); this.setNotifyContext(notifyContext); };
此外,Observer类还有一个很重要的方法,就是Observer对象接收到消息执行的notifyObserver()方法:
/** * Notify the interested object. * * @param {puremvc.Notification} notification * The Notification to pass to the interested objects notification method * @return {void} */ Observer.prototype.notifyObserver= function (notification) { this.getNotifyMethod().call(this.getNotifyContext(), notification); };
上面的代码的意思是在context(回调函数执行作用域)中调用notify方法(回调函数)。
关于Observer类基本上就这几点了,一是notify和context两个属性,二是构造函数中对两个属性的初始化,三是notifyObserver()。接下来的博客会讲notifier(通知者类)。
最后,同样分享一张之前学PureMVC做的思维导图:
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步