js观察者模式

    var Event = {
    callbacks: {},

    on: function (eventName, callback) {
      //你的代码
      if (!this.callbacks[eventName]) {
        this.callbacks[eventName] = [];
        this.callbacks[eventName].push(callback)
      }
      else {
        this.callbacks[eventName].push(callback)
      }
    },

    emit: function (eventName, parameter) {
      //你的代码
      if (!this.callbacks[eventName]) {
        return false
      }
      else {
        while (this.callbacks[eventName].length > 0) {
          this.callbacks[eventName].shift().call(this, parameter)
        }
      }
    }
  };
  Event.on('test', function (result) {
    console.log(result);
  });
  Event.on('test', function () {
    console.log('test');
  });
  Event.emit('test', 'hello world'); // 输出 'hello world' 和 'test'

  var person1 = {};
  var person2 = {};
  Object.assign(person1, Event);
  Object.assign(person2, Event);
  person1.on('call1', function () {
    console.log('person1');
  });
  person2.on('call2', function () {
    console.log('person2');
  });
  person1.emit('call1'); // 输出 'person1'
  person1.emit('call2'); // 没有输出
  person2.emit('call1'); // 没有输出
  person2.emit('call2'); // 输出 'person2'

你可能感兴趣的:(js观察者模式)