search
HomeWeb Front-endJS TutorialDetailed explanation of writing custom events in JavaScript_Basic knowledge

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 are event, customevent and dispatchevent.

to customize events directly, 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. used in combination:

// 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:

// 绑定自定义事件
$(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 custom events are self-customized events that are different from standard events such as click, submit, etc. before describing the benefits of custom events, let’s look at an example of a custom event:

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

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 the event.

yes, the mechanism of custom events is the same as that of ordinary events - listen to the event, write the callback operation, and execute the callback 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, as you may have guessed, 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 = 'customevent',callback 为开发者实际定义的回调函数
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 make the custom event mechanism cooperate with the monitoring and simulation triggering of standard events, a complete event mechanism is given here. this mechanism supports the monitoring, removal of monitoring and simulation triggering operations of standard events and custom events. 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 );
测试用例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);

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. then enter testbox.remove('customconsole', triggeragain) to remove the pair. for the latter listener, use testbox.trigger('customconsole') to trigger a 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 are working normally.

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
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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