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

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

  • 相关阅读:
    HDU4366 Successor 线段树+预处理
    POJ2823 Sliding Window 单调队列
    HDU寻找最大值 递推求连续区间
    UVA846 Steps 二分查找
    HDU3415 Max Sum of MaxKsubsequence 单调队列
    HDU时间挑战 树状数组
    UVA10168 Summation of Four Primes 哥德巴赫猜想
    UESTC我要长高 DP优化
    HDUChess 递推
    HDU4362 Dragon Ball DP+优化
  • 原文地址:https://www.cnblogs.com/youngC/p/2625852.html
Copyright © 2011-2022 走看看