rxjs 怎么使用_使用RxJS Observables进行SUPER SAIYAN

rxjs 怎么使用

I loved DragonBall Z as a kid, and still love it as an adult.

我从小就爱DragonBall Z,但从小到大仍然喜欢它。

Among the ludicrous number of transformations, the original Super Saiyan remains my favorite.

在可笑的转换数量中,原始的超级赛亚人仍然是我的最爱。

Nothing quite like the original

没有什么比原来的

I’m also loving RxJS the more I level up with it, so why not combine these two for the ultimate showdown?

我越喜欢RxJS,就越喜欢RxJS,那么为什么不将两者结合起来进行最终的对决呢?

我们去超级赛亚人 (Let’s Go Super Saiyan)

With four sprite sheets and a bit of HTML, CSS, and RxJS, we can recreate this legendary transformation!

通过四个Sprite工作表以及一些HTML,CSS和RxJS,我们可以重新创建这个传奇的转换!

This is what we’ll be making. Exciting, right?! ?

这就是我们要做的。 令人兴奋,对吗? ?

建立 (Setup)

Everything’s on my GitHub.

一切都在我的GitHub上 。

cd ./wherever-you-want
git clone [https://github.com/yazeedb/dbz-rxjs](https://github.com/yazeedb/dbz-rxjs)
cd dbz-rxjs

Open index.html in your favorite browser, and the project in your favorite text editor, and you’re ready to go!

在您喜欢的浏览器中打开index.html ,然后在您喜欢的文本编辑器中打开该项目,就可以开始了!

No npm installs today ?

今天没有npm install吗?

And going forward, I’ll use the acronym “SSJ” instead of “Super Saiyan” for brevity.

为了简便起见,我将使用缩写词“ SSJ”代替“ Super Saiyan”。

训练的第一天 (First Day of Training)

You’ll notice that Goku’s already moving. Since we’re focusing on RxJS, we’ll just skim the project’s starting point.

您会注意到悟空已经在移动了。 由于我们专注于RxJS,因此我们将略过项目的起点。

Here’s the main HTML:

这是主要HTML:

<div id="root"><div id="meter-container"><span>Hold any key to POWER UP!</span><div id="meter"></div></div><div id="sprite" class="base"></div>
</div>

The bottom div has class="base", which corresponds to this CSS:

底部div具有class="base" ,它对应于以下CSS:

.base,
.ssj {width: 120px;height: 250px;animation: stand 0.8s steps(2) infinite;
}.base {background-image: url('img/goku-standing-sheet.png');
}

This sets Goku’s width, height, and standing animation.

设置悟空的宽度,高度和站立动画。

If you look at his base/ssj sprite sheets, it’s two different positions and we’re switching between them every 0.8 seconds.

如果您查看他的base / ssj Sprite表,它是两个不同的位置,我们每0.8秒切换一次。

The switching’s handled towards the bottom of style.css:

切换处理到style.css的底部:

@keyframes stand {from {background-position: 0px;}to {background-position: -255px;}
}

Same thing for power up:

上电相同:

@keyframes powerup {from {background-position: 0px;}to {background-position: -513px;}
}

We’ll cover the power up meter when we manipulate it.

在操作电表时,我们将对其进行介绍。

掌握DOM元素 (Mastering the DOM Elements)

index.html already includes RxJS@6.2.1 via CDN, so you’re covered.

index.html已经通过CDN包含RxJS@6.2.1 ,因此您已RxJS@6.2.1

In app.js, let’s capture the DOM elements we’re interested in:

app.js ,让我们捕获我们感兴趣的DOM元素:

const sprite = document.querySelector('#sprite');
const meterContainer = document.querySelector('#meter-container');
const meter = document.querySelector('#meter');

I prefer to alias document.querySelector so using it doesn’t cause me wrist pain.

我更喜欢给document.querySelector加上别名,因此使用它不会引起手腕疼痛。

const $ = document.querySelector.bind(document);**
const sprite = $('#sprite');
const meterContainer = $('#meter-container');
const meter = $('#meter');

Next, we’ll create a main function and immediately call it.

接下来,我们将创建一个main函数并立即调用它。

// ...const main = () => {// do something
};
main();

上电 (Powering Up)

Here is main’s first code snippet:

这是main的第一个代码段:

const main = () => {const { fromEvent } = rxjs;const begin = fromEvent(document, 'keydown');const end = fromEvent(document, 'keyup');
};

Goku should power up when a key is held down, and stop when that key is let go. We can use the fromEvent operator to create two observables:

按下某个键时,悟空应该上电,放开该键时应该停止。 我们可以使用fromEvent运算符来创建两个可观察对象:

  • begin: Notifies when the user presses a key down.

    begin :通知当用户按下一个键下来

  • end: Notifies whenever the user lets go of a key.

    end :在用户放开任何按键时通知。

Then we can subscribe to these emissions and act upon them. To get the power up animation, give sprite the powerup class name.

然后,我们可以订阅这些排放并对其采取行动。 要获得加电动画,请给spritepowerup类别名称。

begin.subscribe(() => {sprite.classList.add('powerup');
});

It works, but pressing a key causes him to power up forever…

可以,但是按一个键会使他永远通电……

We must also subscribe to the end observable, so we know when the key has been let go.

我们还必须订阅可观察的end ,以便我们知道何时释放密钥。

end.subscribe(() => {sprite.classList.remove('powerup');
});

Now he powers up and down at your command.

现在,他根据您的命令上下电。

建立童子军 (Building a Scouter)

Any DBZ fan has seen a scouter, the little eyewear used to track power levels (until like episode 20…).

任何DBZ粉丝都曾经看到过一个窥探者,那是用来追踪功率水平的小眼镜(直到第20集…)。

Obligatory > 9000 joke

强制性> 9000笑话

As Saiyans power up, their power level grows. Inconceivable, right?

随着赛亚人的力量上升,他们的力量水平也在增长。 不可思议吧?

We need a way to track Goku’s power level as he ascends, and trigger the SSJ transformation after say, 100 points.

我们需要一种方法来跟踪悟空在他上升时的功率水平,并在说出100分之后触发SSJ转换。

We can start his power off at 1, and increase it while the user holds a key down.

我们可以从1开始关闭电源,然后在用户按住键的同时增加电源。

RxJS运算符 (RxJS Operators)

Operators are where RxJS really shines. We can use pure functions to describe how data should transform through the stream.

操作员是RxJS真正发挥作用的地方。 我们可以使用纯函数来描述数据应如何在流中进行转换。

When the user holds a key down, let’s transform those emissions into a number that increases over time.

当用户按下某个键时,让我们将这些排放量转换为随时间增加的排放量。

扫瞄 (Scan)

The scan operator is perfect for this. It’s like Array.reduce, but it emits as it’s reducing.

扫描运算符非常适合此操作。 这就像Array.reduce ,但它发出的,因为它的减少

For example, if you have an array of numbers:

例如,如果您有一个数字数组:

nums = [1, 2, 3, 4, 5];

And wish to add them up, reduce is a great choice.

并希望将它们加起来, reduce是一个不错的选择。

nums.reduce((a, b) => a + b, 0);
// 15

What if you want to see each addition as it happens?

如果您希望每次添加时都能看到该怎么办?

Enter scan. You can run this in our app’s console.

输入scan 。 您可以在我们的应用程序控制台中运行它。

const { from } = rxjs;
const { scan } = rxjs.operators;from([1, 2, 3, 4, 5]).pipe(scan((a, b) => a + b, 0)).subscribe(console.log);// 1 (0 + 1)
// 3 (1 + 2)
// 6 (3 + 3)
// 10 (6 + 4)
// 15 (10 + 5)

See how the emissions increase over time? We can do that with Goku as he powers up!

看看排放量如何随时间增加? 我们可以通过悟空加电来做到这一点!

const { fromEvent } = rxjs;
const { scan, tap } = rxjs.operators;const begin = fromEvent(document, 'keydown');
const end = fromEvent(document, 'keyup');begin.pipe(scan((level) => level + 1, 1),tap((level) => {console.log({ level });})).subscribe(() => {sprite.classList.add('powerup');});

We start his level at 1 and increase it by 1 every time the keydown event fires.

我们将他的级别从1开始,并在每次keydown事件触发时将其级别提高1。

And the tap operator operator lets us quickly log the value without disturbing the pipeline.

轻敲运算符运算符使我们可以快速记录该值,而不会打扰管道。

My power infinitely approaches MAXIMUM!

我的力量无限接近最大值!

超级赛亚人 (Going Super Saiyan)

We’ve trained hard, it’s time to transform.

我们经过艰苦的训练,是时候转型了。

The scan operator tracks Goku’s power level. Now we need to go SSJ when it emits 100.

scan操作员跟踪悟空的功率水平。 现在我们需要在SSJ发出100信号时使用它。

I built a map of levels: transformations. You can put it right above main.

我建立了一个levels: transformations 。 您可以将其放在main上方。

const powerLevels = {100: {current: 'base',next: 'ssj'}
};const main = () => {// ...
};

It’s overkill, but should simplify adding future transformations.

这太过分了,但是应该简化添加将来的转换的过程。

When the power level reaches a number in that powerLevels map, we’ll remove its current class from sprite and add the next class.

当功率级别达到该powerLevels映射中的一个数字时,我们将从sprite删除其current类并添加next类。

This lets us smoothly go from one transformation to the next.

这使我们能够顺利地从一种转换过渡到另一种转换。

Here’s the code.

这是代码。

const { fromEvent } = rxjs;
const { filter, map, scan, tap } = rxjs.operators;const begin = fromEvent(document, 'keydown');
const end = fromEvent(document, 'keyup');begin.pipe(scan((level) => level + 1, 1),tap((level) => {console.log({ level });sprite.classList.add('powerup');}),map((level) => powerLevels[level]),filter((level) => level && level.next)).subscribe(({ current, next }) => {sprite.classList.remove(current);sprite.classList.add(next);});

地图和过滤器 (Map and Filter)

Adding the powerup class now happens inside of tap, because it should always happen. The SSJ transformation however, shouldn’t always happen.

现在添加powerup类发生在tap ,因为它应该总是发生。 但是,SSJ转换不应该总是发生。

Using map, the latest power level becomes an entry in the powerLevels map. We use filter to check if the entry exists and has a .next property.

使用map ,最新功率级别将成为powerLevels映射中的一个条目。 我们使用filter检查条目是否存在具有.next属性。

If it does, that means Goku can go even further beyond! Our .subscribe will swap current and next as class names on sprite.

如果可以,那就意味着悟空可以走得更远! 我们的.subscribe将在sprite上交换current名称和next作为类名。

The end result?

最终结果?

功率计 (Power Meter)

You’re having as much fun as I am, right? Unfortunately, our user won’t.

你和我一样开心,对吧? 不幸的是,我们的用户不会。

They can’t see how high Goku’s power level is! They won’t know how to open the DevTools console. We must remedy this!

他们看不到悟空的功率等级有多高! 他们不知道如何打开DevTools控制台。 我们必须对此进行补救!

Let’s improve our UX by filling the power meter. You can put this above main.

让我们通过填充功率计来改善用户体验。 您可以将其放在main之上。

const fillMeter = (level) => {const limit = 100;if (level >= limit) {return;}const containerWidth = meterContainer.offsetWidth;const newWidth = (level / limit) * containerWidth;meter.style.width = `${newWidth}px`;
};

And call it inside tap.

并在tap调用它。

tap((level) => {console.log({ level });sprite.classList.add('powerup');fillMeter(level);
});

And here we go:

现在我们开始:

走得更远 (Going Even Further Beyond)

Unlocking more transformations is just a matter of adding sprites, and updating our powerLevels map. If you’re interested, submit a PR on the repo and we’ll definitely talk.

解锁更多转换只是添加精灵,并更新我们的powerLevels映射。 如果您有兴趣,请在仓库中提交PR,我们一定会谈。

Here’s the original sprite sheet. Enjoy!

这是原始的精灵表 。 请享用!

翻译自: https://www.freecodecamp.org/news/go-super-saiyan-with-rxjs-observables-d4681ae51930/

rxjs 怎么使用

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393354.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java编程石头剪刀布_java 开发的石头,剪刀,布的游戏 demo

[java]代码库/** 创建一个类Game&#xff0c;石头&#xff0c;剪刀&#xff0c;布的游戏。*/public class Game {/*** param args*/String[] s {"石头","剪刀","布"};//获取电脑出拳String getComputer(int i){String computerGuess s[i];retur…

JList的基本操作

1.初始化并添加元素 DefaultListModel leftListModelnew DefaultListModel(); String[] items Model.getPairs(); for (int i0; i<items.length; i) { leftListModel.add(i, items[i]); } JList leftLstnew JList(leftListModel); 2.删除所有元素 leftListModel.remove…

请求WebApi的几种方式

请求WebApi的几种方式目前所了解的请求WebAPI的方式有通过后台访问api 和通过js 直接访问api接口 首先介绍下通过后台访问api的方法&#xff0c;可以使用HttpClient的方式也可以使用WebRequest的方式 1、HttpClient的方式 &#xff08;1&#xff09;Get请求 string url "…

Django第三篇

前端反向解析 应用场景&#xff1a;通过访问a路由&#xff0c;到达a的对应视图函数&#xff0c;函数到达对应的前端a标签 a标签的路径是b路由&#xff0c;如果我们在后端改变b路由的路径&#xff0c;那么a标签便无法访问 到b路由&#xff0c;只能手动在前端改变a标签的路径&…

leetcode792. 匹配子序列的单词数

给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。 示例: 输入: S “abcde” words [“a”, “bb”, “acd”, “ace”] 输出: 3 解释: 有三个是 S 的子序列的单词: “a”, “acd”, “ace”。 class Solution {public int numMatchingSubseq(Strin…

react context_使用React Context API-入门

react contextLets use the React Context API to change theme in an app!让我们使用React Context API更改应用程序中的主题&#xff01; 但是首先&#xff0c;一些背景 &#xff01; &#xff1f; (But first, some context! ?) Ok terrible puns aside lets have a look …

redis本地及远程登录

redis默认只能localhost登录&#xff0c;所以需要开启远程登录。解决方法如下&#xff1a;一、在redis的配置文件redis.conf中&#xff0c;找到bind 127.0.0.11、去掉 #bind 127.0.0.1前面的#号注释&#xff0c;将bind 127.0.0.1 改成了bind 0.0.0.0&#xff08;这样不限制连接…

java初始化变量n_java中预构造函数初始化变量的属性

在Java中,可以在调用构造函数之前初始化编程变量.public class StockGraph extends JPanel {public boolean runUpdates true;double TickMarks 18;double MiddleTick TickMarks / 2;double PriceInterval 5;double StockMaximum;double StockMinimum;Random testStockValu…

烦了

桃花飞绿水 一庭芳草围新绿 有情芍药含春泪 野竹上青霄 十亩藤花落古香 无力蔷薇卧晓枝 我愿暂求造化力 减却牡丹妖艳色 花非花 梦非梦 花如梦 梦似花 梦里有花 花开如梦 心非心 镜非镜 心如镜 镜似心 镜中有心 心如明镜 ​​转载于:https://www.cnblogs.com/langdao/p/1099281…

js图片库 案例

事件处理函数&#xff1a;事件处理函数的作用是&#xff0c;在特定事件发生时调用特定的JavaScript代码。本例中想要在用户点击某个链接的时候触发一个动作&#xff0c;所以需要使用onclick事件处理函数。 添加事件处理函数的语法&#xff1a; event"JavaScript statement…

hitchhiker部署_《 Hitchhiker的React Router v4指南》:路由配置的隐藏值

hitchhiker部署Welcome to the Hitchhiker’s Guide to React Router v4, Part IV!欢迎来到《 React Router v4旅行者指南》&#xff0c;第四部分&#xff01; Now that we’ve learned about recursive routes, let’s get back to our initial boilerplate, to avoid mixing…

亮剑:PHP,我的未来不是梦(11)

2. 再说说“必备能力”说道能力&#xff0c;很多应届毕业生都愿意给自己的点评是“我的学习能力很强”或者是“具有良好的学习意识”等。这里存在着这样一个误区&#xff01;把企业当成了学校&#xff01;当成了试验室&#xff01;把老板当成了老师&#xff01;作为用人单位&am…

leetcode457. 环形数组循环

给定一个含有正整数和负整数的环形数组 nums。 如果某个索引中的数 k 为正数&#xff0c;则向前移动 k 个索引。相反&#xff0c;如果是负数 (-k)&#xff0c;则向后移动 k 个索引。因为数组是环形的&#xff0c;所以可以假设最后一个元素的下一个元素是第一个元素&#xff0c;…

Jquery的ajax提交成功后刷新页面

转载于:https://www.cnblogs.com/huoxiansudi/p/6646855.html

程序员编程经验_在没有实际编程的情况下成为更好的程序员

程序员编程经验In this talk, Ryan Johnson explains what was for him the invisible step to becoming a better developer.在演讲中&#xff0c;瑞安约翰逊(Ryan Johnson)解释了对他来说&#xff0c;成为更好的开发人员这一无形的步骤。 You can watch the full video on t…

粘贴复制

方法1: 方法二: 方法三: // 第三种 ios 设备和 android设备均正常,但是pc端没有//定义函数window.Clipboard (function(window, document, navigator) { var textArea, copy; // 判断是不是ios端 function isOS() { return navigator.userAgent.mat…

leetcode109. 有序链表转换二叉搜索树(递归)

给定一个单链表&#xff0c;其中的元素按升序排序&#xff0c;将其转换为高度平衡的二叉搜索树。本题中&#xff0c;一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。示例:给定的有序链表&#xff1a; [-10, -3, 0, 5, 9],一个可能的答案是…

mxnet教程

官方教程&#xff0c;讲的还行&#xff0c;我用自己的实例讲解。自己如何设计网络&#xff0c;自己的迭代器 1&#xff1a;引入module&#xff1a; import mxnet as mx import numpy as np import cv2 import matplotlib.pyplot as plt import logginglogger logging.getLogge…

web动画_Web动画简介

web动画by CodeDraken由CodeDraken Web动画简介 (An Introduction to Web Animations) In this introduction to web animations article, we will cover basic CSS animations using pseudo-classes, transitions, and transformations.在此Web动画简介中&#xff0c;我们将介…

java统计空间占用_JVM —— Java 对象占用空间大小计算

引用类型(reference type&#xff1a; Integer)在 32 位系统上每一个占用 4bytes(即32bit&#xff0c; 才干管理 2^324G 的内存), 在 64 位系统上每一个占用 8bytes(开启压缩为 4 bytes)。四. 对齐填充HotSpot 的对齐方式为 8 字节对齐。不足的须要 Padding 填充对齐&#xff0…