zoukankan      html  css  js  c++  java
  • Observer pattern in 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?

  • 相关阅读:
    GitLab的基础使用-汉化配置
    GitLab的基础使用-数据备份与恢复
    Apache Hadoop集群扩容实战案例
    Hadoop 集群-完全分布式模式(Fully-Distributed Mode)
    HDFS参数调优总结
    网站压力测试 工具webbench
    2013年十大必知的大数据分析公司
    做电子商务网上开店应该读的书
    教你用大功率路由器覆盖3平方公里的WiFi广告
    中央推进城镇化建设 六行业分享25万亿蛋糕
  • 原文地址:https://www.cnblogs.com/sanshi/p/1504812.html
Copyright © 2011-2022 走看看