search
HomeWeb Front-endJS TutorialBasic knowledge of writing custom events in JavaScript

Basic knowledge of writing custom events in JavaScript

Nov 28, 2017 pm 02:02 PM
javascriptbasic knowledgecustomize

Custom events are different from events with browser-specific behaviors (similar to click, mouseover, submit, keydown and other events). The event name can be defined at will, and can be added and triggered through specific methods. and delete. In this article, we will talk about the basics of writing custom events in JavaScript.

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

Customize the event directly and 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) ;


CustomEvent can create a more highly customized event and can also attach some data. The specific usage is as follows:


var myEvent = new CustomEvent(eventname, options);


## where options can be:


{

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


Detail can store some initialization information and can be 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);



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


Using custom events requires attention to compatibility issues, but using jQuery is much simpler:


// Bind custom event

$(element).on('myCustomEvent', function(){});

// Trigger event
$(element). trigger('myCustomEvent');
In addition, you can pass more parameter information when triggering a custom event:

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


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



//Create event var evt = document.createEvent('Event'); //Define event type evt.initEvent('customEvent', true, true); //Listen to events on the element var obj = document.getElementById('testBox'); obj.addEventListener('customEvent', function(){ console.log('customEvent event triggered'); }, false);


#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. Indicates 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 is a custom event, such as type = 'customEvent', callback is the callback function actually defined by the developer

obj[type] = 0;
obj[type]++;

obj.attachEvent('onpropertychange', function(event){
if( event.propertyName == type ){
callback.call(obj) ;
}
});


The principle of this method is actually to add a custom attribute to the DOM and at the same time listen to the propertychange event of the element. When the value of a property of the DOM changes, the propertychange callback will be triggered, and the occurrence will be judged in the callback. Whether the changed attribute is our custom attribute, 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('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 );

Test case 1 (custom event test)

// 测试用例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);


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 content is the basic knowledge of writing custom events in JavaScript. I hope it can help everyone.

Related recommendations:

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

Successfully solved the custom event and solved the BUG of repeated requests

How to create a custom event in JavaScript

Custom events in javascript

javascript A preliminary study on custom events_javascript skills

The above is the detailed content of Basic knowledge of writing custom events in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool