Home Web Front-end JS Tutorial Detailed explanation of how to implement custom event code examples in JavaScript

Detailed explanation of how to implement custom event code examples in JavaScript

Jul 22, 2017 pm 04:35 PM
javascript js customize

We can customize events to achieve more flexible development. Events can be a very powerful tool when used properly. Event-based development has many advantages (described later).

The functions related to custom events include Event, CustomEvent and dispatchEvent.

Directly customize the event, use the Event constructor:


var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);
// Dispatch the event.
elem.dispatchEvent(event);
Copy after login

CustomEvent can create a more highly customized event, and can also attach some data, specific usage As follows:


##

var myEvent = new CustomEvent(eventname, options);
Copy after login

where options can be:


{
  detail: {
    ...
  },
  bubbles: true,
  cancelable: false
}
Copy after login

where detail can store some initialization information, which can be in Called when triggered. Other properties define whether the event has bubbling functions and so on.

Built-in events will be triggered by the browser based on certain operations, while custom events need to be triggered manually. The dispatchEvent function is used to trigger an event:


element.dispatchEvent(customEvent);
Copy after login

The above code indicates that the customEvent event is triggered on element. The combination is:


// 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);
Copy after login

You need to pay attention to compatibility issues when using custom events, but using jQuery is much simpler:


// 绑定自定义事件
$(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" ] );
});
Copy after login

JavaScript custom events are customized events that are different from standard events such as click and submit. Before describing the benefits of custom events, let’s look at an example of a custom event:


<p id="testBox"></p>

// 创建事件
var evt = document.createEvent(&#39;Event&#39;);
// 定义事件类型
evt.initEvent(&#39;customEvent&#39;, true, true);
// 在元素上监听事件
var obj = document.getElementById(&#39;testBox&#39;);
obj.addEventListener(&#39;customEvent&#39;, function(){
  console.log(&#39;customEvent 事件触发了&#39;);
}, false);
Copy after login

For specific effects, you can view the Demo. Enter obj.dispatchEvent(evt) in the console. You can see that "customEvent event is triggered" is output in the console, indicating that the custom event is successfully triggered.

In this process, the createEvent method creates an empty event evt, then uses the initEvent method to define the event type as the agreed custom event, then monitors the corresponding element, and then uses dispatchEvent to trigger event.

Yes, the mechanism of custom events is the same as that of ordinary events - listen to events, write callback operations, and execute callbacks after the event is triggered. But the difference is that custom events are completely controlled by us when they are triggered, which means a kind of JavaScript decoupling is achieved. We can flexibly control multiple related but logically complex operations using the custom event mechanism.

Of course, you may have guessed that the above code does not take effect in lower versions of IE. In fact, createEvent() is not supported in IE8 and lower versions of IE, but there is IE's private fireEvent. () method, but unfortunately, fireEvent only supports the triggering of standard events. Therefore, we can only use a special and simple method to trigger custom events.


// type 为自定义事件,如 type = &#39;customEvent&#39;,callback 为开发者实际定义的回调函数
obj[type] = 0;
obj[type]++;
 
obj.attachEvent(&#39;onpropertychange&#39;, function(event){
  if( event.propertyName == type ){
    callback.call(obj);
  }
});
Copy after login

The principle of this method is actually to add a custom attribute to the DOM and listen to the propertychange event of the element. When the value of a certain attribute of the DOM changes, The propertychange callback will be triggered, and then it will be judged in the callback whether the changed property is our custom property. If so, the callback actually defined by the developer will be executed. This simulates the mechanism of custom events.

In order to enable the custom event mechanism to cooperate with the monitoring and simulation triggering of standard events, a complete event mechanism is given here. This mechanism supports the monitoring of standard events and custom events, and removes monitoring and simulation. Trigger action. It should be noted that in order to make the logic of the code clearer, it is agreed that custom events are prefixed with 'custom' (for example: 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(&#39;custom&#39;) != -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(&#39;onpropertychange&#39;, fnEv);
 
        // 在元素上存储绑定的 propertychange 的回调,方便移除事件绑定
        if( !_that.element[&#39;callback&#39; + callback] ){
     
          _that.element[&#39;callback&#39; + callback] = fnEv;
 
        }
    
      // 标准事件处理
      } else {
    
        _that.element.attachEvent(&#39;on&#39; + type, callback);
      }
       
    } else {
       
      /**
       * @supported For Others
       */
       
      _that.element[&#39;on&#39; + 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(&#39;custom&#39;) != -1 ){
 
        // 移除对相应的自定义属性的监听
        _that.element.detachEvent(&#39;onpropertychange&#39;, _that.element[&#39;callback&#39; + callback]);
 
        // 删除储存在 DOM 上的自定义事件的回调
        _that.element[&#39;callback&#39; + callback] = null;
      
      // 标准事件的处理
      } else {
      
        _that.element.detachEvent(&#39;on&#39; + type, callback);
      
      }
 
    } else {
       
      /**
       * @supported For Others
       */
       
      _that.element[&#39;on&#39; + 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(&#39;Event&#39;);
        // 定义事件的类型
        evt.initEvent(type, true, true);
        // 触发事件
        _that.element.dispatchEvent(evt);
      // IE
      } else if(_that.element.fireEvent){
         
        if( type.indexOf(&#39;custom&#39;) != -1 ){
 
          _that.element[type]++;
 
        } else {
 
          _that.element.fireEvent(&#39;on&#39; + type);
        }
    
      }
 
    } catch(e){
 
    };
 
    return _that;
       
  }
}
 
Ev.fn.init.prototype = Ev.fn;
 
})( window );
测试用例1(自定义事件测试)

// 测试用例1(自定义事件测试)
// 引入事件机制
// ...
// 捕捉 DOM
var testBox = document.getElementById(&#39;testbox&#39;);
// 回调函数1
function triggerEvent(){
    console.log(&#39;触发了一次自定义事件 customConsole&#39;);
}
// 回调函数2
function triggerAgain(){
    console.log(&#39;再一次触发了自定义事件 customConsole&#39;);
}
// 封装
testBox = $(testBox);
// 同时绑定两个回调函数,支持链式调用
testBox.add(&#39;customConsole&#39;, triggerEvent).add(&#39;customConsole&#39;, triggerAgain);
Copy after login
The complete code is in Demo.

After opening the Demo, call testBox.trigger('customConsole') in the console to trigger the custom event yourself. You can see that the console outputs two prompts, and then enter testBox.remove('customConsole', triggerAgain) Remove the last listener, and then use testBox.trigger('customConsole') to trigger the custom event. You can see that the console only outputs a prompt, that is, the last listener is successfully removed. At this point, all functions of the event mechanism work normally.

The above is the detailed content of Detailed explanation of how to implement custom event code examples in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

How to customize x-axis and y-axis in excel? (How to customize excel axis scale) How to customize x-axis and y-axis in excel? (How to customize excel axis scale) Mar 14, 2024 pm 02:10 PM

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles