JavaScript Native Implementation Viewer pattern

Source: Internet
Author: User
Tags emit event listener object model

The observer pattern, also called the Publish-subscribe pattern, defines a one-to-many relationship that allows multiple observer objects to listen to a Subject object at the same time, notifying all observers when the subject's state changes. It is composed of two types of objects, subject and observer, the topic is responsible for publishing events, while observers subscribe to these events to observe the subject, the Publisher and Subscribers are fully decoupled, do not know each other's existence, both share only a custom event name.

Native support for this pattern was achieved through eventemitter in Nodejs.

In JavaScript, the event listener mechanism can be understood as an observer pattern. Event binding is performed through the onclick, which is then triggered by an interactive behavior or by an event's active triggering.

Here is a JS custom pubsub, read the following code carefully to help you understand the observer pattern.

First, the definition of the Observer class PubSub

/* Pubsub */ function Pubsub(){ //存放事件和对应的处理方法 this.handles = {}; }

Second, implement event subscription on

//传入事件类型type和事件处理handle on: function (type, handle) {     if(!this.handles[type]){ this.handles[type] = []; } this.handles[type].push(handle); }

III. implementation of event release emit

Emitfunction (//get event type by passing in parameter var type = array.prototype.shift.call ( arguments); if (! This.handles[type]) {return  False } for (var i = 0; i < this.handles[type].length; i++) {var handle = Span class= "Hljs-keyword" >this.handles[type][i]; //execution event handle.apply (this,  arguments); } }  

The Array.prototype.shift.call (arguments) code is required, and the arguments object is a built-in object of function that can get the real parameter group passed in when the method is called.
The shift method takes the first parameter in the array, which is type.

Iv. implementing an event cancellation subscription off

off: function (type, handle) {     handles = this.handles[type]; if(handles){ if(!handle){ handles.length = 0;//清空数组 }else{ for (var i = 0; i < handles.length; i++) { var _handle = handles[i]; if(_handle === handle){ handles.splice(i,1); } } } } }

Full code:

/* Pubsub */functionPubsub (){Storage events and corresponding processing methodsThis.handles = {}; } pubsub.prototype={Incoming event type types and event handling handle on:function (Type, handle) {if (!this.handles[Type]) {this.handles[Type] = []; }this.handles[Type].push (handle); }, Emit:function () {Getting event types by passing in parametersVarType =Array.prototype.shift.call (arguments);if (!this.handles[Type]) {ReturnFalse }for (var i =0; I <this.handles[Type].length; i++) {var handle =this.handles[Type][i];//execution event handle.apply (this,  arguments); }}, off: function (type, handle) {handles = this.handles[type]; Span class= "Hljs-keyword" >if (handles) {if (!handle) {handles.length = 0; //Empty Array} else{for (var i = 0; i < handles.length; i++) {var _handle = handles[i]; if (_handle = = handle) {Handles.splice (I,1);}}} } } } 

V. Testing

var P1 =New Pubsub (); P1.on (' mm ',function (Name) {Console.log (' mm: ' + name '); }); P1.emit (' mm ',' haha haha ');Console.log (' =============== ');var P2 =New Pubsub ();var fn =function (Name) {Console.log (' mm2: ' + name '); };var fn2 =function (name) {console.log ( ' mm2 ', FN); P2.on ( ' mm2 ', fn2); P2.emit ( ' mm2 ',  ' ha 2 ha 2 ha 2 ha 2 '); console.log ( '-------------');p 2.off (  ' mm2 ', FN); P2.emit ( ' mm2 ',  ' ha 2 ha 2 ha 2 ha 2 '); console.log ( '-------------');p 2.off (  mm2 '); P2.emit ( ' mm2 ',  ' ha 2 ha 2 ha 2 ha 2 '); console.log ( '-------------');      

For JavaScript Technical Essentials article please see Shanghai Shang School: "JavaScript Document Object Model Dom", "JS building JavaScript", "detail JavaScript BOM" and so on, please pay attention to.

JavaScript Native Implementation Viewer pattern

Related Article

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.