为了账号安全,请及时绑定邮箱和手机立即绑定

Observer pattern in JavaScript

标签:
JavaScript
The observer pattern (a subset of the asynchronous publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

Many times, i saw the observer word. For example, in extjs there is a Ext.util.Observable class.

Abstract base class that provides a common interface for publishing events. Subclasses are expected to to have a property “events” with all the events defined.

I look at the code and find something like this:

Ext.util.Observable = function() { };
Ext.util.Observable.prototype = (function() {       

    return {   

          addListener : function(eventName, fn, scope, o){   

          },   

          removeListener : function(eventName, fn, scope){   

          }   

    };   

})();

Seems it just an abstract class to maintain functions relation to events.
I didn’t understand the inside logic of observer until i saw this article.
It’s about new feature of ASP.NET4.0 AJAX PREVIEW - JavaScript Observer Pattern, implemented in Sys.Observer.

First, there is an old-plain javascript object:

var latestPost = {title:"JavaScript Observer Patter", url:"..."};
function initComponent() {
    $("").attr("href", latestPost.url).html(latestPost.title).appendTo("body");
}

We use this object to create a hyperlink in the DOM.
Second, After a period of time, we retrieve the latest post from server and update latestPost object. The question is how to notify the iniComponent function to execute again?

With the help of Sys.Observer in ASP.NET 4.0 AJAX PREVIEW:

Sys.Observer.makeObservable(latestPost);
Sys.Observer.addPropertyChanged(latestPost, iniComponent);
latestPost.beginUpdate();
latestPost.setValue("title", "I want an iphone.");
latestPost.endUpdate();

When you call the endUpdate function, the function iniComponent registered in lastedPost object has to be execute again.

 You see, the Sys.Observer’s logic should not much complex, which manage event callbacks and add some functions to the plain-old object. When the functions are called, just trigger the callbacks.

It’s clear - Observer, right?

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消