The visitor pattern of javascript object-oriented programming design pattern

function Input(inputDom) {
  this.visitiors = {
    'click': [],
    'change': [],
    'special': []
  };
  this.inputDom = inputDom
}

First define an element to initialize the data structure.

Input.prototype.on = function (eventType, callback) {
  if (typeof this.visitiors[eventType] !== 'undefined') {
    this.visitiors[eventType].push(callback)
  }
};

Input.prototype.off = function (eventType,callback) {
  var visitors = this.visitiors[eventType];
  if(typeof visitors !== 'undefined'){
    var index = visitors.indexOf(callback);
    if(index > 0){
      visitors.splice(index,1)
    }
  }
};

Step 2: Expose an interface for adding visitors and an interface for deleting visitors.

Input.prototype.trigger = function (eventType,event) {
  var visitor = this.visitiors[eventType];
  var eventFormat = processEvent(event);
  if(typeof visitor !== 'undefined'){
    for(var i = 0;i<visitor.length;i++){
      visitor[i](eventFormat)
    }
  }
}

The third step is to define a method, through which input can establish a relationship with the visitor, or the visitor has dnalf subscribed to the receiver for messages, and once the receiver receives the message, it will be delivered to its visitors one by one.

 

 

Next is how to use:

let a = new Input(this.p)
console.log(a)
a.on('click',function () {
  console.log(333)
});
a.trigger('click')

An Input is instantiated here, then a method is added to click, and then the trigger method is called, so that the function added through the visitor mode on the Input can be triggered: a.on('click', function() {}). This is my understanding of the visitor pattern.

There is also the method of off, which is not very clear. It would be good if there is a great God to guide it. Learning the front end is all about self-study!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324440898&siteId=291194637