July 3rd, 2019 Today Wednesday plans

July 3rd, 2019 Today Wednesday plans

  • Learn custom event
  • Summary document
  • Complete schedule

Custom events
What events?

  1. The main event is the way JavaScript and browser interactions.
  2. Event is called the observer design pattern, which is called to create loosely coupled code technology.

Objects can publish events to indicate that the object life cycle of an interesting time to come. Then other objects can be observed the object, wait for these funny moments come and run the code.
The observer pattern consists of two types of objects: the body and the observer .

  • The main body responsible for issuing event, at the same time observer to observe the subject by subscribing to these events. A key concept of the model is the main viewer does not know anything, that can exist independently and operate normally even if the observer does not exist.
  • Observer knows the body and can register event callback function (event handler).

When it comes to the DOM, DOM is the subject of your event-handling code is an observer.

Interact with the DOM event is the most common way, but they can also be used for non DOM code - by implementing a custom event. Custom concept behind the event is to create an object management events , so that other objects monitor those events. The basic model can achieve this function is defined as follows:

//自定义事件
function EventTarget(){
    //用来储存事件处理程序
    this.handlers = {}
}

EventTarget.prototype = {
    constructor: EventTarget,
    //用于注册给定类型的事件的事件处理程序
    addHandler: function(type,handler){
        //这里的this是?
        console.log(this);
        if(typeof this.handlers[type] == 'undefined'){
            this.handlers[type] = []
        }
        this.handlers[type].push(handler);
    },
    //用于触发一个事件
    fire: 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;i<handlers.length;i++){
                handlers[i](event);
            }
        }
    },
    //用于注销某个事件类型的事件处理程序
    removeHandler: function(type,handler){
       if(this.handlers[type] instanceof Array){
            var handlers = this.handlers[event.type];
            for(var i=0;i<handlers.length;i++){
                if(handlers[i] === handler){
                    break;
                }
            }
            handlers.splice(i,1);
       } 
    }
}
function handleMessage(event){
    console.log('Message Received',event.message);
}
//创建一个新对象
var target = new EventTarget();
//添加一个事件处理程序
target.addHandler('message',handleMessage);
//触发事件
target.fire({type: "message",message:"Hello,World!"});
//删除事件处理程序
//target.removeHandler('message',handleMessage);

//再次调应用程序
//target.fire({type: "message",message:"Hello,World!"});

Complete schedule: 50%

Guess you like

Origin blog.csdn.net/boysky0015/article/details/94553153