Observer pattern in JavaScript

來源:互聯網
上載者:User
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?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.