• 自定义事件


    转自《高级javascript程序设计第二版》。

    在看YUI的时候,本来对自定义事件的了解不是那么深的,但看了《高》之后,对这个功能有了更深入的了解。的确是个很棒的思路。

    ===============================================

    function EventTarget(){

        this.handlers = {};

    }

    EventTarget.prototype = {

       constructor : EventTarget,

       adddHandler : function(type,handler){

           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,len = handlers.length;i<len;i++){

                handlers[i](event);

             }

          }

       },

       removeHandler : function(type,handler){

           if (this.handlers[type] instance of Array){

              var handlers = this.handlers[type];

              for ( var i=0,len=handlers.length;i<len;i++){

                 if (handlers[i] === handler){

                      break;

                 }

              }

              handlers.splice(i,1);

           }

       }

    };

    function handleMessage(event){

        alert("Message received: " + event.message);

    }

    var target = new EventTarget();

    target.addHandler("message",handleMessage);

    target.fire({type : "message",message : "hello world"});

    target.removeHandler("message",handleMessage);

    function Person(name,age){

       EventTarget.call(this);

       this.name = name;

       this.age = age;

    }

    extend(Person,EventTarget);

    Person.prototype.say = function(message){

        this.fire({type:"message",message:message});

    }

    var person = new Person("adang",26);

    person.addHandler("message",handleMessage);

    person.say("Hi there");

  • 相关阅读:
    初涉Django与MySQL连接
    Mysql数据库操作常用命令
    解决远程登录MYSQL数据库
    全集网影片下载
    LR学习资料
    LR性能测试说明
    fiddler
    Axure(快速原型设计工具)
    httpwatch
    Appscan(安全性测试工具)
  • 原文地址:https://www.cnblogs.com/cly84920/p/4426634.html
Copyright © 2020-2023  润新知