AMP 中的事件

虽然不能直接使用 JS,但 AMP 提供了一些事件以实现一些简单的交互


在 AMP 中通过 on 属性添加事件

1
2
3
4
<!-- tap 表示事件的类型 -->
<!-- warning-message 表示要操作的元素 id -->
<!-- 元素后面连接着的 .hide 指具体的动作(我要让这个元素干嘛) -->
<button on="tap:warning-message.hide">Cool, thanks!</button>

除了所有元素都可以使用的 tap 事件(被点击/轻触)之外,AMP 针对不同类型的元素也提供了相应的事件

同样的,也提供了多样的动作(actions)用来实现各种效果,比如 showhidetoggleClass


Events in JS

我们来看下其他和事件相关的内容

1
myButton.addEventListener('click', function(){ alert('Hello, world!') })

或者

1
<button onclick="alert('Hello, world!')">

这是我们最早接触的添加事件的方法

通过事件处理函数,我们可以得到 event 参数,在 event 下面又有一些常用的属性和方法

Difference between e.target and e.currentTarget 里讲到区别两者的方法

e.target = The thing under the mouse (as ben says… the thing that triggers the event).
e.currentTarget = The thing before the dot… (see below)

推荐一下JavaScript Event Propagation,把事件的传播描述得比较清楚

Event capturing is not supported in all browsers and rarely used. For instance, Internet Explorer prior to version 9.0 does not support event capturing.

Also, event capturing only works with event handlers registered with the addEventListener() method when the third argument is set to true. The traditional method of assigning event handlers, like using onclick, onmouseover, etc. won’t work here.

Events in Vue

而在 Vue 中,我们通过 v-on (或者是它的简写 @)这个指令来为元素添加事件

1
2
3
4
5
<!-- 表达的意思一目了然,click 是事件的类型,'count += 1' 是事件发生之后的动作 -->
<div id="example-1">
<button v-on:click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div>

Vue 还提供了事件修饰符,用以方便地处理一些非常常见的需求,从而把注意力集中到逻辑中去

另外,对于一个指令来说修饰符和事件名称一样,都是指令的参数,并不是什么神奇的魔法

Events in React

1
2
3
4
5
6
7
8
9
// 在一个组件类里添加 render 方法,在其中绑定 click 事件
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick.bind(this)}>
You {text} this. Click to toggle.
</p>
);
}

在 React 中添加事件也非常简单

需要注意的是

注意要显式调用 bind(this) 将事件函数上下文绑定要组件实例上,这也是 React 推崇的原则:没有黑科技,尽量使用显式的容易理解的 JavaScript 代码。

关于 bind 可以看看这篇文章,React JS — Ways of binding events

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2019/11/20/AMP-event/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

整合 Springboot-Activiti-Vue 流程定义