当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 详解JavaScript中的自定义事件编写

详解JavaScript中的自定义事件编写

2019年07月30日  | 移动技术网IT编程  | 我要评论

我们可以自定义事件来实现更灵活的开发,事件用好了可以是一件很强大的工具,基于事件的开发有很多优势(后面介绍)。

与自定义事件的函数有 event、customevent 和 dispatchevent。

直接自定义事件,使用 event 构造函数:

var event = new event('build');

// listen for the event.
elem.addeventlistener('build', function (e) { ... }, false);

// dispatch the event.
elem.dispatchevent(event);

customevent 可以创建一个更高度自定义事件,还可以附带一些数据,具体用法如下:

var myevent = new customevent(eventname, options);

其中 options 可以是:

{
  detail: {
    ...
  },
  bubbles: true,
  cancelable: false
}

其中 detail 可以存放一些初始化的信息,可以在触发的时候调用。其他属性就是定义该事件是否具有冒泡等等功能。

内置的事件会由浏览器根据某些操作进行触发,自定义的事件就需要人工触发。dispatchevent 函数就是用来触发某个事件:

element.dispatchevent(customevent);

上面代码表示,在 element 上面触发 customevent 这个事件。结合起来用就是:

// add an appropriate event listener
obj.addeventlistener("cat", function(e) { process(e.detail) });

// create and dispatch the event
var event = new customevent("cat", {"detail":{"hazcheeseburger":true}});
obj.dispatchevent(event);

使用自定义事件需要注意兼容性问题,而使用 jquery 就简单多了:

// 绑定自定义事件
$(element).on('mycustomevent', function(){});

// 触发事件
$(element).trigger('mycustomevent');
此外,你还可以在触发自定义事件时传递更多参数信息:

$( "p" ).on( "mycustomevent", function( event, myname ) {
 $( this ).text( myname + ", hi there!" );
});
$( "button" ).click(function () {
 $( "p" ).trigger( "mycustomevent", [ "john" ] );
});

javascript 自定义事件就是有别于如 click, submit 等标准事件的自行定制的事件,在叙述自定义事件有何好处之前,先来看一个自定义事件的例子:

<div id="testbox"></div>

// 创建事件
var evt = document.createevent('event');
// 定义事件类型
evt.initevent('customevent', true, true);
// 在元素上监听事件
var obj = document.getelementbyid('testbox');
obj.addeventlistener('customevent', function(){
  console.log('customevent 事件触发了');
}, false);

具体效果可以查看 demo,在 console 中输入 obj.dispatchevent(evt),可以看到 console 中输出“customevent 事件触发了”,表示自定义事件成功触发。

在这个过程中,createevent 方法创建了一个空事件 evt,然后使用 initevent 方法定义事件的类型为约定好的自定义事件,再对相应的元素进行监听,接着,就是使用 dispatchevent 触发事件了。

没错,自定义事件的机制如普通事件一样——监听事件,写回调操作,触发事件后执行回调。但不同的是,自定义事件完全由我们控制触发时机,这就意味着实现了一种 javascript 的解耦。我们可以把多个关联但逻辑复杂的操作利用自定义事件的机制灵活地控制好。

当然,可能你已经猜到了,上面的代码在低版本的 ie 中并不生效,事实上在 ie8 及以下版本的 ie 中并不支持 createevent(),而有 ie 私有的 fireevent() 方法,但遗憾的是,fireevent 只支持标准事件的触发。因此,我们只能使用一个特殊而简单的方法触发自定义事件。

// type 为自定义事件,如 type = 'customevent',callback 为开发者实际定义的回调函数
obj[type] = 0;
obj[type]++;
 
obj.attachevent('onpropertychange', function(event){
  if( event.propertyname == type ){
    callback.call(obj);
  }
});

这个方法的原理实际上是在 dom 中增加一个自定义属性,同时监听元素的 propertychange 事件,当 dom 的某个属性的值发生改变时就会触发 propertychange 的回调,再在回调中判断发生改变的属性是否为我们的自定义属性,若是则执行开发者实际定义的回调。从而模拟了自定义事件的机制。

为了使到自定义事件的机制能配合标准事件的监听和模拟触发,这里给出一个完整的事件机制,这个机制支持标准事件和自定义事件的监听,移除监听和模拟触发操作。需要注意的是,为了使到代码的逻辑更加清晰,这里约定自定义事件带有 'custom' 的前缀(例如:customtest,customalert)。

/**
 * @description 包含事件监听、移除和模拟事件触发的事件机制,支持链式调用
 *
 */
 
(function( window, undefined ){
 
var ev = window.ev = window.$ = function(element){
 
  return new ev.fn.init(element);
};
 
// ev 对象构建
 
ev.fn = ev.prototype = {
 
  init: function(element){
 
    this.element = (element && element.nodetype == 1)? element: document;
  },
 
  /**
   * 添加事件监听
   * 
   * @param {string} type 监听的事件类型
   * @param {function} callback 回调函数
   */
 
  add: function(type, callback){
 
    var _that = this;
     
    if(_that.element.addeventlistener){
       
      /**
       * @supported for modern browers and ie9+
       */
       
      _that.element.addeventlistener(type, callback, false);
       
    } else if(_that.element.attachevent){
       
      /**
       * @supported for ie5+
       */
 
      // 自定义事件处理
      if( type.indexof('custom') != -1 ){
 
        if( isnan( _that.element[type] ) ){
 
          _that.element[type] = 0;
 
        } 
 
        var fnev = function(event){
 
          event = event ? event : window.event
           
          if( event.propertyname == type ){
            callback.call(_that.element);
          }
        };
 
        _that.element.attachevent('onpropertychange', fnev);
 
        // 在元素上存储绑定的 propertychange 的回调,方便移除事件绑定
        if( !_that.element['callback' + callback] ){
     
          _that.element['callback' + callback] = fnev;
 
        }
    
      // 标准事件处理
      } else {
    
        _that.element.attachevent('on' + type, callback);
      }
       
    } else {
       
      /**
       * @supported for others
       */
       
      _that.element['on' + type] = callback;
 
    }
 
    return _that;
  },
 
  /**
   * 移除事件监听
   * 
   * @param {string} type 监听的事件类型
   * @param {function} callback 回调函数
   */
   
  remove: function(type, callback){
 
    var _that = this;
     
    if(_that.element.removeeventlistener){
       
      /**
       * @supported for modern browers and ie9+
       */
       
      _that.element.removeeventlistener(type, callback, false);
       
    } else if(_that.element.detachevent){
       
      /**
       * @supported for ie5+
       */
       
      // 自定义事件处理
      if( type.indexof('custom') != -1 ){
 
        // 移除对相应的自定义属性的监听
        _that.element.detachevent('onpropertychange', _that.element['callback' + callback]);
 
        // 删除储存在 dom 上的自定义事件的回调
        _that.element['callback' + callback] = null;
      
      // 标准事件的处理
      } else {
      
        _that.element.detachevent('on' + type, callback);
      
      }
 
    } else {
       
      /**
       * @supported for others
       */
       
      _that.element['on' + type] = null;
       
    }
 
    return _that;
 
  },
   
  /**
   * 模拟触发事件
   * @param {string} type 模拟触发事件的事件类型
   * @return {object} 返回当前的 kjs 对象
   */
   
  trigger: function(type){
 
    var _that = this;
     
    try {
        // 现代浏览器
      if(_that.element.dispatchevent){
        // 创建事件
        var evt = document.createevent('event');
        // 定义事件的类型
        evt.initevent(type, true, true);
        // 触发事件
        _that.element.dispatchevent(evt);
      // ie
      } else if(_that.element.fireevent){
         
        if( type.indexof('custom') != -1 ){
 
          _that.element[type]++;
 
        } else {
 
          _that.element.fireevent('on' + type);
        }
    
      }
 
    } catch(e){
 
    };
 
    return _that;
       
  }
}
 
ev.fn.init.prototype = ev.fn;
 
})( window );
测试用例1(自定义事件测试)

// 测试用例1(自定义事件测试)
// 引入事件机制
// ...
// 捕捉 dom
var testbox = document.getelementbyid('testbox');
// 回调函数1
function triggerevent(){
    console.log('触发了一次自定义事件 customconsole');
}
// 回调函数2
function triggeragain(){
    console.log('再一次触发了自定义事件 customconsole');
}
// 封装
testbox = $(testbox);
// 同时绑定两个回调函数,支持链式调用
testbox.add('customconsole', triggerevent).add('customconsole', triggeragain);

完整的代码在 。

打开 demo 后,在 console 中调用 testbox.trigger('customconsole') 自行触发自定义事件,可以看到 console 输出两个提示语,再输入 testbox.remove('customconsole', triggeragain) 移除对后一个监听,这时再使用 testbox.trigger('customconsole') 触发自定义事件,可以看到 console 只输出一个提示语,即成功移除后一个监听,至此事件机制所有功能正常工作。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网