zoukankan      html  css  js  c++  java
  • jQuery事件高级应用EventListener/EventHandler(一)

    概述

    在Web前端开发中,我们经常会遇到以下需求:在渲染一个页面前需要执行function1, function2,function3... 在渲染页面后需要执行function4, function5, function6...在将后台数据绑定到页面前要执行function7, function8...在数据绑定到页面后要执行function9, function10...

    主要代码如下

    View Code
    var EventListener = function () {};
    EventListener.prototype = {
      ns: 'co',
      event: {},
      handlerPool: {},
      widget: function () {
        return $(document);
      },
      trigger: function (type, data) {
        if (!this.accept(type)) {
          return false;
        }
        this.__bindHandlers(type);

        var e = $.Event(type + '.' + this.ns);
        e.options = data;
        return this.widget().trigger(e);
      },
      register: function (type, handler) {
        if (!this.accept(type) || !handler) {
          return false;
        }

        if ($.isFunction(handler)) {
          handler = $.extend(new EventHandler(), {
            handle: handler
          });
        }

        var eventType = type;
        var handlers = this.handlerPool[eventType] || [];
        handlers.push(handler);
        this.handlerPool[eventType] = handlers;
      },
      unregister: function (type, handler) {
        if (!this.accept(type)) {
          return false;
        }

        var handlers = this.handlerPool[type];
        if (handler && handlers) {
          var leftHandlers = $.grep(handlers, function (obj) {
            return obj.handle !== handler;
          });
          if (leftHandlers.length && leftHandlers.length < handlers.length) {
            this.handlerPool[type] = leftHandlers;
          }
          return;
        }

        delete this.handlerPool[type];
      },
      accept: function (type) {
        var accepted = false;

        $.each(this.event, function (key, name) {
          if (name === type) {
            accepted = true;
            return false;
          }
        });
        return accepted;
      },
      __bindHandlers: function (type) {
        var self = this;

        if (type) {
          self.widget().unbind(type + '.' + this.ns);

          var handlers = this.handlerPool[type] || [];
          $.each(handlers, function (i, handler) {
            self.widget().bind(type + '.' + self.ns, handler.data || {}, handler.handle);
          });
        }
      }
    };

    var EventHandler = function () {};

    EventHandler.prototype.__type = 'EventHandler';

    EventHandler.prototype.handle = function () {
      return this;
    };

    具体如何使用,下次再将吧...

  • 相关阅读:
    python读写excel利器:xlwings 从入门到精通
    认识--类 ( Class ) 面向对象技术
    python 平均值/MAX/MIN值 计算从入门到精通
    python读写word文档 -- python-docx从入门到精通
    【模板】KMP算法
    【模板】主席树
    C语言第一次博客作业
    C语言--第0次作业
    Chapter5:语句
    Chapter4:表达式
  • 原文地址:https://www.cnblogs.com/youngC/p/2625852.html
Copyright © 2011-2022 走看看