zoukankan      html  css  js  c++  java
  • JS的自定义事件(观察者模式)

     1      var Event = {
     2             on: function (eventName, callback) {
     3                 console.log("eventName:"+eventName)
     4                 if (!this.handles) {
     5                     Object.defineProperty(this, "handles", {
     6                         value: {},
     7                         enumerable: false//不可枚举
     8                     })
     9                     //this.handles = {};//可以枚举
    10                 }
    11                 if (!this.handles[eventName]) {
    12                     this.handles[eventName] = [];
    13                 }
    14                 this.handles[eventName].push(callback);
    15             },
    16             emit: function () {
    17                 var hlist = this.handles[arguments[0]] || [];
    18                 for (var i = 0; i < hlist.length; i++) {
    19                     this.handles[arguments[0]][i](arguments[1]);
    20                 }
    21             }
    22         }
    23         Event.on("dome", function (params) {
    24             console.log(params);
    25         });
    26         Event.on("dome", function (params) {
    27             console.log("dome log");
    28         });
    29         Event.emit("dome", "holle world");
    30 
    31         var person1 = {};
    32         var person2 = {};
    33         //Object.assign是浅复制,会导致person1,person2共用同一个handles
    34         Object.assign(person1, Event);
    35         Object.assign(person2, Event);
    36         person1.on('call1', function () {
    37             console.log('person1');
    38         });
    39         person2.on('call2', function () {
    40             console.log('person2');
    41         });
    42         person1.emit('call1'); // 输出 'person1'
    43         person1.emit('call2'); // 没有输出
    44         person2.emit('call1'); // 没有输出
    45         person2.emit('call2'); // 输出 'person2'
  • 相关阅读:
    赋值问题
    构造方法的作用
    this的使用
    三目运算符和形参的使用
    构造方法作用:给所有对象进行相同的初始化操作
    成员变量和局部变量
    相关开发的书籍名汇集
    html ---- web sql 例子
    让input表单输入框不记录输入过信息的方法
    css实现两端对齐的3种方法
  • 原文地址:https://www.cnblogs.com/cn2758/p/8079043.html
Copyright © 2011-2022 走看看