This time I will bring you JavaScript event management, What are the precautions for using JavaScript event management, the following is a practical case, let’s take a look take a look.
When designing JavaScript xxsdk, we considered allowing callers to participate in the workflow, and started using callback functions. As follows:
this.foo = function(args,callbackFn) { //do something //then if callbackFn is a function callbackFn(); };
Or pass in config during initialization.
function SDK(config) { var configs = { onInit: function() { }, onFoo: function () { }, // on.... }; //合并参数 configs = $.extend(configs, config); this.foo = function (args) { //do something configs.onFoo(); }; }
But here comes the problem. As there are more functions, the first method becomes very annoying. The parameters of each method must be followed by one or more callback functions. The code seems unclean, and only the user The callback will only be executed when it is called, and it will not be used for methods that are not exposed to the user. In the second way, the more functions there are, the longer the config will be and the construction code will look ugly. On the other hand, one method will only trigger one callback. Finally, the following method was used
Event Management
First define an event manager. The main idea is to have each event type correspond to a callback list, so that the external world can associate multiple events with the same event. Second-rate. Canceling an association is to remove a callback function from the function list of that event type. Triggering is to execute all the functions in the list. Of course, parameters are also included.
var eventManger = { handlers: {}, //类型,绑定事件 addHandler:function(type,handler) { if (typeof this.handlers[type] == "undefined") { this.handlers[type] = [];//每个事件都可以绑定多次 } this.handlers[type].push(handler); }, removeHandler:function(type, handler) { var events = this.handlers[type]; for (var i = 0, len = events.length; i <p style="text-align: left;">Then publish the association and removal methods in the sdk: </p><pre class="brush:php;toolbar:false"> //给外部绑定事件 this.on = function(type, event) { eventManger.addHandler(type,event); }; //移除事件 this.off = function(type, event) { eventManger.removeHandler(type, event); };
Trigger events respectively during the execution process:
this.init = function() { //do init eventManger.trigger('init'); }; this.start = function() { //do start eventManger.trigger('start'); }; this.connect = function() { eventManger.trigger('connect'); }; this.messages = function() { var msgs = []; msgs.push("你好吗"); msgs.push("我很好"); eventManger.trigger('messages',msgs); }; this.disconnect = function() { eventManger.trigger('disconnect'); };
Then the user will compare when using it convenient.
//绑定connect sdk.on('connect', function () { console.log('connect'); });//绑定messages sdk.on('messages', function (data) { if (!data) return; if (data instanceof Array) { for (var i = 0; i <p style="text-align: left;">You can also bind it first, remove it and then bind it. </p><pre class="brush:php;toolbar:false">var oninit = function() { console.log('init...'); }; sdk.on('init', oninit); sdk.on('init', function () { console.log('other init'); }); sdk.off('init', oninit); sdk.init();
All codes:
function SDK() { var eventManger = { handlers: {}, //类型,绑定事件 addHandler:function(type,handler) { if (typeof this.handlers[type] == "undefined") { this.handlers[type] = [];//每个事件都可以绑定多次 } this.handlers[type].push(handler); }, removeHandler:function(type, handler) { var events = this.handlers[type]; for (var i = 0, len = events.length; i <p style="text-align: left;">View Code</p><p style="text-align: left;">Execution results: </p><p style="text-align: left;"><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/061/021/90ac8234e9699492d50c725f11bf054a-2.jpg?x-oss-process=image/resize,p_40" class="lazy" alt=""></p><p style="max-width:90%">You can also extend some methods once( ), removeListener(), <em>removeAllListeners(), etc. </em></p><p style="text-align: left;">Summary: The event processing method is more concise and more scalable. The event mechanism of <a href="http://www.php.cn/wiki/1495.html" target="_blank">jquery</a> does not bind event listening functions to DOM elements, but is managed based on the data cache module. For reference here, all listening <a href="http://www.php.cn/wiki/60.html" target="_blank"> objects </a>handleObj of the same event type type form the listening object array handles. Because there is no <a href="http://www.php.cn/code/5682.html" target="_blank">dom operation</a> involved, it is relatively simple. </p><p> I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! </p><p>Recommended reading:</p><p style="text-align: left;"><a href="http://www.php.cn/weixin-kaifa-388825.html" target="_blank">Asp.Net MVC development for WeChat scan code payment</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/css-tutorial-388822.html" target="_blank">How to use the gradient of ss3</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/js-tutorial-388820.html" target="_blank">Detailed explanation of Promise in jQuery, Angular and node</a><br></p>
The above is the detailed content of JavaScript event management. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools