Learning JavaScript Design Patterns The Observer Pattern
The Observer Pattern
The Observer is a design pattern where an object (known as a subject) maintains a list of objects depending on it (observers), automatically notifying them of any changes to state.
When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers (which can include specific data related to the topic of the notification).
When we no longer wish for a particular observer to be notified of changes by the subject they are registered with, the subject can remove them from the list of observers.
It's often useful to refer back to published definitions of design patterns that are language agnostic to get a broader sense of their usage and advantages over time. The definition of the Observer pattern provided in the GoF book, Design Patterns: Elements of Reusable Object-Oriented Software, is:
"One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject's state, they can simply detach themselves."
We can now expand on what we've learned to implement the Observer pattern with the following components:
- Subject: maintains a list of observers, facilitates adding or removing observers
- Observer: provides a update interface for objects that need to be notified of a Subject's changes of state
- ConcreteSubject: broadcasts notifications to observers on changes of state, stores the state of ConcreteObservers
- ConcreteObserver: stores a reference to the ConcreteSubject, implements an update interface for the Observer to ensure state is consistent with the Subject's
First, let's model the list of dependent Observers a subject may have:
function ObserverList(){
this.observerList = [];
} ObserverList.prototype.add = function( obj ){
return this.observerList.push( obj );
}; ObserverList.prototype.count = function(){
return this.observerList.length;
}; ObserverList.prototype.get = function( index ){
if( index > -1 && index < this.observerList.length ){
return this.observerList[ index ];
}
}; ObserverList.prototype.indexOf = function( obj, startIndex ){
var i = startIndex; while( i < this.observerList.length ){
if( this.observerList[i] === obj ){
return i;
}
i++;
} return -1;
}; ObserverList.prototype.removeAt = function( index ){
this.observerList.splice( index, 1 );
};
Next, let's model the Subject and the ability to add, remove or notify observers on the observer list.
function Subject(){
this.observers = new ObserverList();
} Subject.prototype.addObserver = function( observer ){
this.observers.add( observer );
}; Subject.prototype.removeObserver = function( observer ){
this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
}; Subject.prototype.notify = function( context ){
var observerCount = this.observers.count();
for(var i=0; i < observerCount; i++){
this.observers.get(i).update( context );
}
};
We then define a skeleton for creating new Observers. The update
functionality here will be overwritten later with custom behaviour.
// The Observer
function Observer(){
this.update = function(){
// ...
};
}
In our sample application using the above Observer components, we now define:
- A button for adding new observable checkboxes to the page
- A control checkbox which will act as a subject, notifying other checkboxes they should be checked
- A container for the new checkboxes being added
We then define ConcreteSubject and ConcreteObserver handlers for both adding new observers to the page and implementing the updating interface. See below for inline comments on what these components do in the context of our example.
HTML:
<button id="addNewObserver">Add New Observer checkbox</button>
<input id="mainCheckbox" type="checkbox"/>
<div id="observersContainer"></div>
Sample script:
// Extend an object with an extension
function extend( extension, obj ){
for ( var key in extension ){
obj[key] = extension[key];
}
} // References to our DOM elements var controlCheckbox = document.getElementById( "mainCheckbox" ),
addBtn = document.getElementById( "addNewObserver" ),
container = document.getElementById( "observersContainer" ); // Concrete Subject // Extend the controlling checkbox with the Subject class
extend( new Subject(), controlCheckbox ); // Clicking the checkbox will trigger notifications to its observers
controlCheckbox.onclick = function(){
controlCheckbox.notify( controlCheckbox.checked );
}; addBtn.onclick = addNewObserver; // Concrete Observer function addNewObserver(){ // Create a new checkbox to be added
var check = document.createElement( "input" );
check.type = "checkbox"; // Extend the checkbox with the Observer class
extend( new Observer(), check ); // Override with custom update behaviour
check.update = function( value ){
this.checked = value;
}; // Add the new observer to our list of observers
// for our main subject
controlCheckbox.addObserver( check ); // Append the item to the container
container.appendChild( check );
}
In this example, we looked at how to implement and utilize the Observer pattern, covering the concepts of a Subject, Observer, ConcreteSubject and ConcreteObserver.
Differences Between The Observer And Publish/Subscribe Pattern
Whilst the Observer pattern is useful to be aware of, quite often in the JavaScript world, we'll find it commonly implemented using a variation known as the Publish/Subscribe pattern. Whilst very similar, there are differences between these patterns worth noting.
The Observer pattern requires that the observer (or object) wishing to receive topic notifications must subscribe this interest to the object firing the event (the subject).
The Publish/Subscribe pattern however uses a topic/event channel which sits between the objects wishing to receive notifications (subscribers) and the object firing the event (the publisher). This event system allows code to define application specific events which can pass custom arguments containing values needed by the subscriber. The idea here is to avoid dependencies between the subscriber and publisher.
This differs from the Observer pattern as it allows any subscriber implementing an appropriate event handler to register for and receive topic notifications broadcast by the publisher.
Here is an example of how one might use the Publish/Subscribe if provided with a functional implementation powering publish()
,subscribe()
and unsubscribe()
behind the scenes:
Learning JavaScript Design Patterns The Observer Pattern的更多相关文章
- Learning JavaScript Design Patterns The Module Pattern
The Module Pattern Modules Modules are an integral piece of any robust application's architecture an ...
- Learning JavaScript Design Patterns The Singleton Pattern
The Singleton Pattern The Singleton pattern is thus known because it restricts instantiation of a cl ...
- Learning JavaScript Design Patterns The Constructor Pattern
In classical object-oriented programming languages, a constructor is a special method used to initia ...
- AMD - Learning JavaScript Design Patterns [Book] - O'Reilly
AMD - Learning JavaScript Design Patterns [Book] - O'Reilly The overall goal for the Asynchronous Mo ...
- use getters and setters Learning PHP Design Patterns
w Learning PHP Design Patterns Much of what passes as OOP misuses getters and setters, and making ac ...
- Learning PHP Design Patterns
Learning PHP Design Patterns CHAPTER 1 Algorithms handle speed of operations, and design patterns ha ...
- [Design Patterns] 3. Software Pattern Overview
When you're on the way which is unknown and dangerous, just follow your mind and steer the boat. 软件模 ...
- JavaScript Design Patterns: Mediator
The Mediator Design Pattern The Mediator is a behavioral design pattern in which objects, instead of ...
- [Design Patterns] 4. Creation Pattern
设计模式是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结,使用设计模式的目的是提高代码的可重用性,让代码更容易被他人理解,并保证代码可靠性.它是代码编制真正实现工程化. 四个关键元素 ...
随机推荐
- JAVA 内存管理总结
1. java是如何管理内存的 Java的内存管理就是对象的分配和释放问题.(两部分) 分配 :内存的分配是由程序完成的,程序员需要通过关键字new 为每个对象申请内存空间 (基本类型除外),所有的对 ...
- Spring MVC常用的注解
@Controller @Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为 类名称开头字母小写,你也可以自己指定,如下 方法一: @Controller ...
- XSS传染基础——JavaScript中的opener、iframe
最近研究XSS,根据etherDream大神的博客 延长XSS生命周期 写了一个子页面父页面相互修改的demo. 一. 子页面.父页面相互修改——window.opener.window.open 在 ...
- to debug asp.net mvc4
Go to Tools -> Options -> Debugger -> General Uncheck the option Enable Just My Code (Manag ...
- Grails默认首页的修改
有些人使用IDEA开发Grails,开发阶段使用Grails自带的默认首页可以方便我们开发,但是开发结束后想要修改默认的首页,如何修改呢? 1.打开grails-app 文件下conf下的UrlMap ...
- 给JavaScript初学者的24条最佳实践(转:http://www.cnblogs.com/yanhaijing/p/3465237.html)
作为“30 HTML和CSS最佳实践”的后续,本周,我们将回顾JavaScript的知识 !如果你看完了下面的内容,请务必让我们知道你掌握的小技巧! 1.使用 === 代替 == JavaScript ...
- C#基础|值类型和引用类型以及传参问题
为了明白什么是值类型和引用类型,先引入你两个概念.堆内存与栈内存 堆内存与栈内存 由于咱的描述能力有限,就不对其下定义了,来看看两者的作用. 共同点: 都是用来存放数据的 不同点: 堆 ...
- 简单的Ajax例子
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 手势识别官方教程(7)识别缩放手势用ScaleGestureDetector.GestureDetector和ScaleGestureDetector.SimpleOnScaleGestureListener
Use Touch to Perform Scaling As discussed in Detecting Common Gestures, GestureDetector helps you de ...
- 使用git批量删除分支
要删除本地,首先要考虑以下三点 列出所有本地分支 搜索目标分支如:所有含有‘dev’的分支 将搜索出的结果传给删除函数 所以我们可以得到: git br |grep 'dev' |xargs git ...