Home > Web Front-end > JS Tutorial > Introduction to JavaScript custom events_javascript skills

Introduction to JavaScript custom events_javascript skills

WBOY
Release: 2016-05-16 17:24:05
Original
1220 people have browsed it

Many DOM objects have native event support. For divs, there are click, mouseover and other events. The event mechanism can bring great flexibility to class design. I believe .net programmers understand this deeply. With the development of web technology, the use of JavaScript to customize objects is becoming more and more frequent. Allowing the objects you create to have an event mechanism and communicating with others through events can greatly improve development efficiency.

Simple event requirements

Events are not optional, they are necessary under certain needs. Take a very simple requirement as an example. Dialog is very common in web development. Each Dialog has a close button. The button corresponds to the close method of the Dialog. The code looks like this

Copy code The code is as follows:



   
        Test
       
   

   

   

   
       
        Dialog

       

       

   


   
        function Dialog(id){
           this.id=id;
           var that=this;
            document.getElementById(id).children[0].onclick=function(){
                that.close();
            }
        }

        Dialog.prototype.show=function(){
           var dlg=document.getElementById(this.id);
            dlg.style.display='block';
            dlg=null;
        }

        Dialog.prototype.close=function(){
           var dlg=document.getElementById(this.id);
            dlg.style.display='none';
            dlg=null;
        }
  

   
        function openDialog(){
           var dlg=new Dialog('dlgTest');
            dlg.show();
        }
  
   

这样在点击button的时候就可以弹出Dialog,点击关闭按钮的时候隐藏Dialog,看起来不错实现了需求,但总感觉缺点儿什么,一般Dialog显示的时候页面还会弹出一层灰蒙蒙半透明的罩子,阻止页面其它地方的点击,Dialog隐藏的时候罩子去掉,页面又能够操作。加些代码添个罩子。

在body顶部添加一个pagecover

为其添加style

复制代码 代码如下:

.pageCover
            {
                width:100%;
                height:100%;
                position:absolute;
                z-index:10;
                background-color:#666;
                opacity:0.5;
                display:none;
            }

为了打开的时候显示page cover,需要修改openDialog方法

复制代码 代码如下:

function openDialog(){
            var dlg=new Dialog('dlgTest');
            document.getElementById('pageCover').style.display='block';
            dlg.show();
        }


Introduction to JavaScript custom events_javascript skills

The effect looks very good. The gray translucent cover covers the buttons on the page after the Dialog pops up. The Dialog is above it. At this time, the problem arises. When the Dialog is closed, the page cover is still there and there is no code. Instead of hiding it, see how the page cover is displayed when it is opened and how it is hidden when it is closed! It really doesn't work. The opening code is defined by the event handler of the page button button. Add a method to display the page cover in it. It's reasonable, but the method of closing Dialog is the logic of the Dialog control (although it is very simple, far from being a control) and has nothing to do with the page. Is it okay to modify the close method of Dialog? No way! There are two reasons. First, Dialog does not know the existence of page cover when it is defined. There is no coupling relationship between the two controls. If the hidden page cover logic is written in the close method of Dialog, then the dialog depends on the page. cover, that is to say, if there is no page cover on the page, the dialog will error. Moreover, when the Dialog is defined, the page cover id of a specific page is not known. There is no way to know which div is hidden. Is it enough to pass in the page cover id when constructing the Dialog? In this way, the two controls no longer have a dependency. , the page cover DIV can also be found through the ID, but what if the user needs to pop up the page cover on some pages and not on others?

This is the time to show off your skills with events. Modify the dialog object and openDialog method

Copy code The code is as follows:

function Dialog(id){
this.id =id;
this.close_handler=null;
var that=this;
document.getElementById(id).children[0].onclick=function(){
that.close();
              if (type of that.close_handler=='function')
                                                 }
}



Copy code The code is as follows:function openDialog(){
var dlg=new Dialog('dlgTest');
document.getElementById('pageCover').style.display='block';

dlg.close_handler=function(){
document.getElementById('page Cover ').style.display='none';
           }
                dlg.show();                                                      

Add a handle inside the Dialog object. The click event handler of the close button will determine whether the handle is a function after calling the close method. If so, it will call and execute the handle. In the openDialog method, after creating the Dialog object, assign the handle to a hidden page cover method, so that the page cover is hidden when the Dialog is closed without causing coupling between the two controls. This interaction process is a simple process of defining events - binding event handlers - triggering events. DOM object events, such as button click events, have a similar principle.

Advanced custom events

The small example given above is very simple, and is far less sophisticated than the DOM itself. This simple event processing has many disadvantages

1. No commonality. If you are defining a control, you have to write a similar structure

2. Event binding is exclusive. Only one close event handler can be bound. Binding a new one will overwrite the previous binding

3. The packaging is not perfect enough. If the user does not know that there is a handle to close_handler, there is no way to bind the event and can only check the source code

Let’s analyze these disadvantages one by one. The first disadvantage is very familiar, and students who have used object-oriented can easily think of the solution - inheritance; for the second disadvantage, a container (two-dimensional array) can be provided to manage all events uniformly. ; The solution to disadvantage three needs to be combined with disadvantage one to add a unified interface to the custom event management object for adding/deleting/triggering events

Copy code The code is as follows:

function EventTarget(){
            this.handlers={};
        }

        EventTarget.prototype={
            constructor:EventTarget,
            addHandler:function(type,handler){
                if(typeof this.handlers[type]=='undefined'){
                    this.handlers[type]=new Array();
                }
                this.handlers[type].push(handler);
            },
            removeHandler:function(type,handler){
                if(this.handlers[type] instanceof Array){
                    var handlers=this.handlers[type];
                    for(var i=0,len=handlers.length;i                        if(handler[i]==handler){
                            handlers.splice(i,1);
                            break;
                        }
                    }
                }
            },
            trigger:function(event){
                if(!event.target){
                    event.target=this;
                }
                if(this.handlers[event.type] instanceof Array){
                    var handlers=this.handlers[event.type];
                    for(var i=0,len=handlers.length;i                        handlers[i](event);
                    }
                }
            }
        }

addHandler方法用于添加事件处理程序,removeHandler方法用于移除事件处理程序,所有的事件处理程序在属性handlers中统一存储管理。调用trigger方法触发一个事件,该方法接收一个至少包含type属性的对象作为参数,触发的时候会查找handlers属性中对应type的事件处理程序。写段代码测试一下。

复制代码 代码如下:

function onClose(event){
alert('message:' event.message);
}

var target=new EventTarget();
target.addHandler ('close',onClose);

                        // The browser can’t help us create the event object,                                                                              'Page Cover closed!'
};

target.trigger(event);



Now that we have solved each of the disadvantages, apply inheritance to solve the first disadvantage. The following is the core code of parasitic combination inheritance. This inheritance method is currently recognized as the best inheritance method in JavaScript

Copy code The code is as follows:function extend(subType,superType){
            var prototype=Object(superType.prototype);
        prototype.constructor=subType;
          subType.prototype=prototype;




Copy code

The code is as follows:




   
        Test
       
   

   
   


   

   

       
       
Dialog

       


       

   


   

   

   

   
   

最后

这样解决了几个弊端看起来就完美多了,其实可以把打开Dialog显示page cover也写成类似关闭时事件的方式了。当代码中存在多个部分在特定时刻相互交互的情况下,自定义事件就非常有用了。如果每个对象都有其它对象的引用,那么整个代码高度耦合,对象改动会影响其它对象,维护起来困难重重。自定义事件使对象解耦,功能隔绝,这样对象之间实现了高聚合。

Related labels:
source:php.cn
Previous article:jQuery animation effect-fadeIn fadeOut fade in and out sample code_jquery Next article:Jquery implements alternating table color changes when the mouse moves over the color change example_jquery
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template