Home > Web Front-end > JS Tutorial > body text

What are the event handling rules in web development?

php中世界最好的语言
Release: 2018-06-04 10:48:55
Original
1643 people have browsed it

This time I will bring you what are the event handling rules in web development, what are the notes of event handling in web development, the following is a practical case, let’s take a look .

Event processing

We know that when an event is triggered, the event object (event object) will be passed into the event handler as a callback parameter. For example:

// 不好的写法function handleClick(event) {  var pop = 
document
.getElementById('popup');
  popup.style.left = event.clientX + 'px';
  popup.style.top = event.clientY + 'px';
  popup.className = 'reveal';
}// 你应该明白addListener函数的意思addListener(element, 'click', handleClick);
Copy after login

This code only uses two attributes of the event object: clientX and clientY. Use these two attributes to position the element before displaying it on the page. Although this code looks very simple and has no problems, it is actually a bad way to write it because this approach has its limitations.

Rule 1: Isolate application logic

The first problem with the above example code is that the event handler contains application logic. Application logic is functional code related to the application, not to user behavior. The application logic in the above example code is to display a pop-up box at a specific location. Although this interaction should occur when the user clicks on a specific element, this is not always the case.

It is a best practice to separate application logic from all event handlers, because you never know when the same logic will be triggered elsewhere. For example, sometimes you need to determine whether to display a pop-up box when the user moves the mouse over an element, or make the same logical judgment when a certain key on the keyboard is pressed. In this way, multiple event handlers execute the same logic, but your code is accidentally copied multiple times.

Another disadvantage of placing application logic in event handlers is related to testing. When testing, you need to trigger the function code directly instead of simulating a click on the element. If your application logic is placed in an event handler, the only way to test it is to cause the event to fire. Although some testing frameworks can simulate triggering events, in practice this is not the best approach to testing. The best way to call functional code is with a single function call.

You always need to separate application logic and event handling code. If you want to refactor the previous example code, the first step is to put the code that handles the pop-up box logic into a separate function. This function is likely to be mounted on a global object defined for the application. The event handler should always be in the same global object, so there are two methods.

// 好的写法 - 拆分应用逻辑var MyApplication = {  handleClick: function (event) {    this.showPopup(event);
  },  showPopup: function (event) {    var pop = document.getElementById('popup');
    popup.style.left = event.clientX + 'px';
    popup.style.top = event.clientY + 'px';
    popup.className = 'reveal';
  }
};
addListener(element, 'click', function (event) {
  MyApplication.handleClick(event);
});
Copy after login

All application logic previously contained in event handlers is now moved to the MyApplication.showPopup() method. Now the MyApplication.handleClick() method only does one thing, which is to call MyApplication.showPopup(). If the application logic is stripped out, calls to the same functional code can occur at multiple points, and there is no need to rely on the triggering of a specific event, which is obviously more convenient. But this is only the first step in breaking down the event handler code.

Rule 2: Do not distribute event objects

After stripping out the application logic, there is still a problem in the above example code, that is, event objects are distributed uncontrollably. It passes MyApplication.handleClick() from the anonymous event handler, which then passes it to MyApplication.showPopup(). As mentioned above, the event object contains a lot of additional information related to the event, and this code only uses two of them. Application logic should not rely on event objects to complete functions correctly for the following reasons:

The method interface does not indicate which data is necessary. A good API must be transparent about expectations and dependencies. Passing an event object as a parameter does not tell you which properties of the event are useful and what they are used for?

Therefore, if you want to test this method, you must recreate an event object and pass it as a parameter enter. Therefore, you need to know exactly what information this method uses so that you can write the test code correctly.

These problems (referring to unclear interface format and self-constructed event objects for testing) are not advisable in large-scale Web applications. Lack of clarity in code can lead to bugs.

The best way is to let the event handler use the event object to handle the event, and then get all the required data and pass it to the application logic. For example, the MyApplication.showPopup() method only requires two pieces of data, the x coordinate and the y coordinate. In this way, we will rewrite the method so that it receives these two parameters.

// 好的写法var MyApplication = {  handleClick: function (event) {    this.showPopup(event.clientX, event.clientY);
  },  showPopup: function (x, y) {    var pop = document.getElementById('popup');
    popup.style.left = x + 'px';
    popup.style.top = y + 'px';
    popup.className = 'reveal';
  }
};
addListener(element, 'click', function (event) {
  MyApplication.handleClick(event);
});
Copy after login

在这段新重写的代码中,MyApplication.handleClick()将x坐标和y坐标传入了MyApplication.showPopup(),代替了之前传入的事件对象。可以很清晰地看到MyApplication.showPopup()所期望传入的参数,并且在测试或代码的任意位置都可以很轻易地直接调用这段逻辑,比如:

// 这样调用非常棒MyApplication.showPopup(10, 10);

当处理事件时,最好让事件处理程序成为接触到event对象的唯一的函数。事件处理程序应当在进入应用逻辑之前针对event对象执行任何必要的操作,包括阻止默认事件或阻止事件冒泡,都应当直接包含在事件处理程序中。比如:

// 好的写法var MyApplication = {  handleClick: function (event) {    // 假设事件支持DOM Level2
    event.preventDefault();
    event.stopPropagation();    // 传入应用逻辑
    this.showPopup(event.clientX, event.clientY);
  },  showPopup: function (x, y) {    var pop = document.getElementById('popup');
    popup.style.left = x + 'px';
    popup.style.top = y + 'px';
    popup.className = 'reveal';
  }
};
addListener(element, 'click', function (event) {
  MyApplication.handleClick(event);
});
Copy after login

在这段代码中,MyApplication.handleClick()是事件处理程序,因此它在将数据传入应用逻辑之前调用了event.preventDefault()和event.stopPropagation(),这清除地展示了事件处理程序和应用逻辑之间的分工。因为应用逻辑不需要对event产生依赖,进而在很多地方都可以轻松地使用相同的业务逻辑,包括写测试代码。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样利用JS做出引用传递与值传递

如何做出node.js界面

The above is the detailed content of What are the event handling rules in web development?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template