Home  >  Article  >  Web Front-end  >  Bubble.js: Efficient 1.6K solutions to common problems

Bubble.js: Efficient 1.6K solutions to common problems

PHPz
PHPzOriginal
2023-08-28 23:21:02817browse

Bubble.js:针对常见问题的高效 1.6K 解决方案

One of the most common tasks in web development is event management. Our JavaScript code typically listens to events dispatched by DOM elements.

This is how we get information from the user: that is, he or she clicked, typed, interacted with our page, and we need to know if that happened. Adding event listeners seems simple, but can be a difficult process.

In this article, we will look at a real case problem and its 1.6K solution.

question

A friend of mine is a junior developer. As such, he didn't have much experience with plain JavaScript; however, he had to start using frameworks like AngularJS and Ember without having a basic understanding of how the DOM relates to JavaScript. While working as a junior developer, he worked on a small project: a single-page event website that involved almost no JavaScript. He came across a small but very interesting problem that ultimately led me to write Bubble.js.

Suppose we have a popup window. A beautifully styled element:

<div class="popup"> ... </div>

This is the code we use to display the message:

var popup = document.querySelector('.popup');
var showMessage = function(msg) {
    popup.style.display = 'block';
    popup.innerHTML = msg;
}
...
showMessage('Loading. Please wait.');

We have another function hideMessage which changes the display property to none and hides the popup. This approach may work for the most general cases, but there are still some problems.

For example, if problems arise one by one, we need to implement additional logic. Suppose we have to add two buttons to the popup's content - Yes and No.

var content = 'Are you sure?<br />';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" class="popup--yes">Yes</a>';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" class="popup--no">No</a>';
showMessage(content);

So, how do we know that the user clicked on them? We have to add event listeners for each link.

For example:

var addListeners = function(yesCB, noCB) {
    popup.querySelector('.popup--yes').addEventListener('click', yesCB);
    popup.querySelector('.popup--no').addEventListener('click', noCB);
}
showMessage(content);
addListeners(function() {
    console.log('Yes button clicked');
}, function() {
    console.log('No button clicked');
});

The above code works the first time it is run. What if we need a new button, or worse, what if we need a different type of button? That is, what if we continue to use the <a></a> element but with a different class name? We can't use the same addListeners function, and it would be annoying to create a new method for each variation of the popup.

Here’s where the problem becomes obvious:

  • We have to add listeners again and again. In fact, we have to do this every time the HTML in the popup's changes.
  • We can attach an event listener only when the popup window's content is updated. Only after showMessage is called. We must always consider this and synchronize both processes.
  • The code that adds the listener has a hard dependency - the popup variable. We need to call its querySelector function instead of document.querySelector. Otherwise, we might select the wrong element.
  • Once we change the logic in the message, we must change the selector and possibly the addEventListener call. It's not dry at all.

There must be a better way to do this.

Yes, there is a better way. No, the solution is not to use a framework.

Before revealing the answer, let’s first talk about events in the DOM tree.

Understanding event handling

Events are an important part of web development. They add interactivity to our applications and act as a bridge between business logic and users. Every DOM element can dispatch events. All we have to do is subscribe to these events and handle the received Event objects.

There is a term "event propagation" which stands for "event bubbling" and "event capturing", both of which are two ways of handling events in the DOM. Let’s see the difference between them using the following notations.

<div class="wrapper">
    <a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b">click me</a>
</div>

We will attach click event handlers to these two elements. However, because they are nested within each other, they will all receive click events.

document.querySelector('.wrapper').addEventListener('click', function(e) {
    console.log('.wrapper clicked');
});
document.querySelector('a').addEventListener('click', function(e) {
    console.log('a clicked');
});

After pressing the link, we will see the following output in the console:

a clicked
.wrapper clicked

So, both elements indeed receive click events. First the link, then . This is the bubbling effect. From the deepest element to its parent. There is a way to stop bubbling. Each handler receives an event object with a stopPropagation method:

document.querySelector('a').addEventListener('click', function(e) {
    e.stopPropagation();
    console.log('a clicked');
});

By using the stopPropagation function we indicate that the event should not be sent to the parent.

Sometimes we may need to reverse the order and let an external element capture the event. To do this we have to use the third parameter in addEventListener. If we pass true as value we will do event capturing. For example:

document.querySelector('.wrapper').addEventListener('click', function(e) {
    console.log('.wrapper clicked');
}, true);
document.querySelector('a').addEventListener('click', function(e) {
    console.log('a clicked');
}, true);

This is how the browser handles events when we interact with the page.

解决方案

好吧,那么我们为什么要在文章中花一部分时间讨论冒泡和捕获呢?我们提到它们是因为冒泡是弹出窗口问题的答案。我们不应该将事件监听器设置为链接,而是直接设置为

var content = 'Are you sure?<br />';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" class="popup--yes">Yes</a>';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" class="popup--no">No</a>';

var addListeners = function() {
    popup.addEventListener('click', function(e) {
        var link = e.target;
    });
}

showMessage(content);
addListeners();

通过遵循这种方法,我们消除了开头列出的问题。

  • 只有一个事件监听器,我们只添加一次。无论我们在弹出窗口中放入什么,事件的捕获都会在其父级中发生。
  • 我们不受附加内容的约束。换句话说,我们不关心 showMessage 何时被调用。只要 popup 变量处于活动状态,我们就会捕获事件。
  • 因为我们调用了 addListeners 一次,所以我们也使用了 popup 变量一次。我们不必保留它或在方法之间传递它。
  • 我们的代码变得灵活,因为我们选择不关心传递给 showMessage 的 HTML。我们可以访问被点击的锚点,因为 e.target 指向被按下的元素。

上面的代码比我们一开始的代码要好。然而,仍然无法以同样的方式发挥作用。正如我们所说, e.target 指向点击的 <a></a> 标签。因此,我们将使用它来区分按钮。

var addListeners = function(callbacks) {
    popup.addEventListener('click', function(e) {
        var link = e.target;
        var buttonType = link.getAttribute('class');
        if(callbacks[buttonType]) {
            callbacks[buttonType](e);
        }
    });
}
...
addListeners({
    'popup--yes': function() {
        console.log('Yes');
    },
    'popup--no': function() {
        console.log('No');
    }
});

我们获取了 class 属性的值并将其用作键。不同的类指向不同的回调。

但是,使用 class 属性并不是一个好主意。它保留用于将视觉样式应用于元素,并且其值可能随时更改。作为 JavaScript 开发人员,我们应该使用 data 属性。

var content = 'Are you sure?<br />';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" data-action="yes" class="popup--yes">Yes</a>';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" data-action="no" class="popup--no">No</a>';

我们的代码也变得更好了。我们可以删除 addListeners 函数中使用的引号:

addListeners({
    yes: function() {
        console.log('Yes');
    },
    no: function() {
        console.log('No');
    }
});

结果可以在这个 JSBin 中看到。

泡泡.js

我在几个项目中应用了上面的解决方案,因此将其包装为一个库是有意义的。它称为 Bubble.js,可在 GitHub 中找到。这是一个 1.6K 的文件,它的作用与我们上面所做的完全一样。

让我们将弹出示例转换为使用 Bubble.js。我们必须更改的第一件事是使用的标记:

var content = 'Are you sure?<br />';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" data-bubble-action="yes" class="popup--yes">Yes</a>';
content += '<a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b" data-bubble-action="no" class="popup--no">No</a>';

我们应该使用 data-bubble-action 而不是 data-action

一旦我们在页面中包含 bubble.min.js ,我们就有了一个全局 bubble 函数。它接受 DOM 元素选择器并返回库的 API。 on 方法是添加监听器的方法:

bubble('.popup')
.on('yes', function() {
    console.log('Yes');
})
.on('no', function() {
    console.log('No');
});

还有一种替代语法:

bubble('.popup').on({
    yes: function() {
        console.log('Yes');
    },
    no: function() {
        console.log('No');
    }
});

默认情况下,Bubble.js 侦听 click 事件,但有一个选项可以更改该设置。让我们添加一个输入字段并监听其 keyup 事件:

<input type="text" data-bubble-action="keyup:input"/>

JavaScript 处理程序仍然接收 Event 对象。因此,在这种情况下,我们可以显示字段的文本:

bubble('.popup').on({
    ...
    input: function(e) {
        console.log('New value: ' + e.target.value);
    }
});

有时我们需要捕获同一元素发出的多个事件而不是一个。 data-bubble-action 接受以逗号分隔的多个值:

<input type="text" data-bubble-action="keyup:input, blur:inputBlurred"/>

在此处查找 JSBin 中的最终变体。

后备

本文提供的解决方案完全依赖于事件冒泡。在某些情况下 e.target 可能不会指向我们需要的元素。

例如:

<div class="wrapper">
    <a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b">Please, <span>choose</span> me!</a>
</div>

如果我们将鼠标放在“choose”上并执行单击,则调度事件的元素不是 <a></a> 标记,而是 span 元素。

摘要

诚然,与 DOM 的通信是我们应用程序开发的重要组成部分,但我们使用框架只是为了绕过这种通信是一种常见的做法。

我们不喜欢一次又一次地添加监听器。我们不喜欢调试奇怪的双事件触发错误。事实上,如果我们了解浏览器的工作原理,我们就能够消除这些问题。

Bubble.js 只是几个小时阅读和一小时编码的结果 - 它是我们针对最常见问题之一的 1.6K 解决方案。

The above is the detailed content of Bubble.js: Efficient 1.6K solutions to common problems. 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