Use JavaScript to implement the observer Mode

Source: Internet
Author: User

First in this article:

The first attempt to translate, original from codeproject (http://www.codeproject.com/jscript/Observer_Pattern_JS.asp)

The first time I used Windows Live writer, beta version.

The first time I wrote in my blog: flyingchen-Suzhou. Net club.

 

ArticleIntroduction:

Anyone who has used JavaScript should be familiar with how to create custom objects through javascript no matter how long it takes. If you don't know how to use OOP in Javascript, you can also look at it. This article uses JavaScript to implement the observer mode.

 

About javascript:

Javascript is a prototype-based learning language (originally called livescript) that has a C-like syntax. Originally, JavaScript was developed by us Netscape for its Navigator browser. Like C, this language does not have its own input or output build method. Just as C depends on the standard input/output function library, the JavaScript engine depends on the host environment. It is an embedded language. In other languages, some use process calls, and some use sub-ProgramAnd some are functions. Javascript coordinates the implementation of other languages, and is uniformly implemented as: custom functions. A major use of JavaScript is to combine with the Web document structure model (DOM), not just HTML to complete functions. JScript, similar to Netscape JavaScript, is used to teach the language of Microsoft IE.

Create a User-Defined Object using JavaScript

Two steps are required to create a JavaScript Object:

Step 1: Create a UDF whose name is the name of the new object. Such a function is similar to a constructor.

Step 2: Create an instance. Like the OO language, with the new operator, the climate closely follows the Object Name and necessary parameters (if any ). The followingCodeDemonstrate how to define a person function and create a person object instance.

 

Function person (name, surname)
{
This. Name = Name;
This. Surname = surname;
}

VaR salvo = new person ('salvatore ', 'vetro ');

This Pointer Points to the current object. You can use this pointer to add or modify attributes of this object.

How to add a method to an object:

In JavaScript, every object that can be created by calling a constructor function has an associated prototype property.

The following syntax is used to add a new method to an object:

Customeobject. Prototype. newmethodname = function;

// Specific case

Person. Prototype. Speak = function (){...}

If you add a new method to the prototype of an object, all instances of this object will have this new method. Note that this prototype is an object. You can also use its syntax to assign values to its attributes and methods:

Function newobject ()

{

Alert ("I am a new object ");

}

Newobject. Prototype =

{

Alert1: unction (STR) {alert (STR),/New Method

Name: 'flyingchen ',

Alert2: function () {alert ('bye')} // New Method

}

VaR newobject = new newobject ();

Newobject. alert1 (newobject. Name );

Newobject. alert2 ();

Each time, when your script tries to read or write an object's attributes, JavaScript searches for the name of the matching attribute in the specific order below. In this order:

    • If the attribute of the current object has been assigned a value, you obtain this value.
    • If the attribute is not assigned a value, check how the constructor assigns a value in the prototype of the attribute.
    • Continue along the prototype chain until any matching property is found (after being assigned a value), or when this matching process is performed until the objects at the most fixed layer. Therefore, if you change the value of the constructed prototype property and do not rewrite the property value in the instance, JavaScript will return the current value of the constructor.

 Class diagram of the observer mode:

The observer mode defines one-to-multiple dependencies between an observed object and multiple observed objects. Therefore, when the state of the observer changes, all the observer objects will know and automatically update their state.

Participants:

    • Subject:

1. Know your own observer

2. provides an interface for adding and detaching observer objects

    • Observer:

1. Define an interface that can be called by subject when the status changes

    • Concretesubject:

1. Stores status information that concreteobserver is interested in

2. Notify the observer when the status changes.

    • Concreteobserver:

1. Have a reference to concretesubject.

2. Save a status information, which should be consistent with that in subject.

3. Implement the observer update interface to maintain coordination with the status information in subject.

 

Collaboration relationship:

1. When the subject status changes, concretesubject sends a message to the observer.

2. After receiving the message, concreteobserver may query the current information of the subject. Concreteobserver uses this information to change its status.

What is next?

Now you know what the observer mode is and how to use JavaScript to create objects. As you can see from the class diagram, You need to define two methods (attach and detach) in your observer class (subject. For this purpose, you need to combine these two operations. Now it's time for you to write arraylist in javascript:

Count --- add --- getat --- clear --- removeat --- insert --- indexof --- lastindexof

 

Function arraylist ()
{
This. alist = []; // initialize with an empty array
}
Arraylist. Prototype. Count = function ()
{
Return this. alist. length;
}
Arraylist. Prototype. Add = function (object)
{
// Object are placed at the end of the array
Return this. alist. Push (object );
}

Arraylist. Prototype. getat = function (INDEX) // index must be a number
{
If (index>-1 & index <this. alist. length)
Return this. alist [Index];
Else
Return undefined; // out of bound array, return undefined
}
Arraylist. Prototype. Clear = function ()
{
This. alist = [];
}

Arraylist. Prototype. removeat = function (INDEX) // index must be a number
{
VaR m_count = This. alist. length;
If (m_count> 0 & index>-1 & index <this. alist. length)
{
Switch (INDEX)
{
Case 0:
This. alist. Shift ();
Break;
Case m_count-1:
This. alist. Pop ();
Break;
Default:
VaR head = This. alist. Slice (0, index );
VaR tail = This. alist. Slice (index + 1 );
This. alist = head. Concat (tail );
Break;
}
}
}

Arraylist. Prototype. Insert = function (object, index)
{
VaR m_count = This. alist. length;
VaR m_returnvalue =-1;

If (index>-1 & index <= m_count)
{
Switch (INDEX)
{
Case 0:
This. alist. unshift (object );
M_returnvalue = 0;
Break;
Case m_count:
This. alist. Push (object );
M_returnvalue = m_count;
Break;
Default:
VaR head = This. alist. Slice (0, index-1 );
VaR tail = This. alist. Slice (INDEX );
This. alist = This. alist. Concat (tail. unshift (object ));
M_returnvalue = index;
Break;
}
}
Return m_returnvalue;
}

Arraylist. Prototype. indexof = function (object, startindex)
{
VaR m_count = This. alist. length;
VaR m_returnvalue =-1;
If (startindex>-1 & startindex <m_count)
{
VaR I = startindex;

While (I <m_count)
{
If (this. alist [I] = Object)
{
M_returnvalue = I;
Break;
}
I ++;
}
}
Return m_returnvalue;
}
Arraylist. Prototype. lastindexof = function (object, startindex)
{
VaR m_count = This. alist. length;
VaR m_returnvalue =-1;
If (startindex>-1 & startindex <m_count)
{
VaR I = m_count-1;
While (I> = startindex)
{
If (this. alist [I] = Object)
{
M_returnvalue = I;
Break;
}
I --;
}
}
Return m_returnvalue;
}

Well, now you can create an observer object and a subject object.

Observer class:

Function Observer ()

{

This. Update = function ()

{

Return;

}

}

Subject Class:

Next, we will implement the three important methods in subject:

Function subject ()

{

This. Observer = new arraylist ();

}

Subject. Prototype. Required y = function (context)
{
VaR m_count = This. Observers. Count ();
For (VAR I = 0; I <m_count; I ++)
This. Observers. getat (I). Update (context );
}

Subject. Prototype. addobserver = function (observer)
{
If (! Observer. Update)
Throw 'wrong parameter ';

This. Observers. Add (observer );
}

Subject. Prototype. removeobserver = function (observer)
{
If (! Observer. Update)
Throw 'wrong parameter ';
This. Observers. removeat (this. Observers. indexof (Observer, 0 ));
}

Inheritance implementation in javascript:

The following methods use JavaScript to simulate the implementation of inheritance. A simple method is to define a method called inherits. Then copy the attribute of the "base class" to the "subclass.

Function inherits (base, extension)
{
For (var property in Base)
{
Try
{
Extension [property] = base [property];
}
Catch (warning ){}
}
}

 

A simple implementation:

Now you need to implement a client so that you can add an observer to the subject. For example, you can create a simple application, define a checkbox as the subject, and define some checkboxes as the observer. When the status of the concrete subject changes, the message is sent to all observers.

* Concrete subject *************/

VaR maincheck = Document. createelement ("input ");

Maincheck. type = 'checkbox ';
Maincheck. ID = 'maincheck ';
Inherits (new subject (), maincheck)

Maincheck ["onclick"] = new function ("maincheck. Y (maincheck. Checked )");

/**************** Observer ******************/</code>

VaR obscheck1 = Document. createelement ("input ");
VaR obscheck2 = Document. createelement ("input ");

Obscheck1.type = 'checkbox ';
Obscheck1.id = 'obs1 ';

Obscheck2.type = 'checkbox ';
Obscheck2.id = 'obs2 ';
Inherits (new observer (), obscheck1)
Inherits (new observer (), obscheck2)

Obscheck1.update = function (value)
{
This. Checked = value;
}

Obscheck2.update = function (value)
{
This. Checked = value;
// Add ........
}
Maincheck. addobserver (obscheck1 );
Maincheck. addobserver (obscheck2 );

// Download the code

2006-8-16

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.