jQuery事件高级应用--EventListener/EventHandler(一)

本文介绍了一种用于Web前端开发的自定义事件监听机制实现方法,该机制允许开发者在页面渲染前后及数据绑定前后触发特定函数,提高代码组织性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

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

主要代码如下

ExpandedBlockStart.gifView 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;
};

 

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

 

转载于:https://www.cnblogs.com/youngC/archive/2012/08/06/2625852.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值