PureMVC(JS版)源码解析(三):Observer类

时间:2022-10-16 12:03:44

      上一篇博客中,我们讲到了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做的思维导图:

PureMVC(JS版)源码解析(三):Observer类