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;
    };

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

  • 相关阅读:
    来谈谈JAVA面向对象
    手把手的SpringBoot教程,SpringBoot创建web项目(一)
    【Java框架型项目从入门到装逼】第十五节
    印章文字识别
    《图像处理实例》之 曲线之间距离求解
    机器学习常用模块
    Ubutu16.04+Cuda9.2/9.0+Cudnn7.12/7.05+TensorFlow-gpu-1.8/1.6
    滑动平均模型原理+源码分析
    AlexNet实践
    TensorFlow NormLization
  • 原文地址:https://www.cnblogs.com/youngC/p/2625852.html
Copyright © 2011-2022 走看看