javascript知识点_一点点JavaScript知识是第1部分很危险的事情

javascript知识点

几乎是一个数据库的奇怪故事 (The Strange Tale of the Almost-a-Database)

这不是教程,这是一个警告性的故事。 (This is not a tutorial, it’s a cautionary tale.)

This is the story of my first web development project, undertaken when the only languages I knew were the big three: HTML, CSS, and Javascript. I had just learned the basics of JQuery, and wanted to get my feet wet with a self-directed project, start to finish — creating a real web app. I just had to decide what to create.

这是我第一个Web开发项目的故事,当时我所知道的唯一的三大语言是HTML,CSS和Javascript。 我刚刚学习了JQuery的基础知识,并想通过一个自我指导的项目弄清自己的脚步,开始完成-创建一个真正的Web应用程序。 我只需要决定要创建什么。

灵感罢工 (Inspiration Strikes)

Inspiration came from my hobbies. A friend of mine was trying his hand at running a tabletop RPG campaign over the web, and bit off a bit more than he could chew. It occurred to me that so much of the stress of running a campaign didn’t just come from the pressure of creative work, but all those little hassles of logistics. Getting all your tools software set up just right. I wanted to create something that would make those hassles a little easier to bear.

灵感来自我的爱好。 我的一个朋友正在尝试通过网络开展桌面RPG广告系列,但付出的努力远远超过了他的咀嚼能力。 在我看来,开展竞选活动的巨大压力不仅来自创意工作的压力,还包括物流方面的所有小麻烦。 正确设置所有工具软件。 我想创造一些东西,使这些麻烦更容易承担。

We had been using the Discrord bot Rythm to pipe in background music for our game sessions, so managing audio in real time was one of the game master’s responsibilities. The DM also had to be a DJ, har har. This would be my opportunity — a simple web tool for automating the process of running the Rythm Bot. All it would take was a little bit of string manipulation to generate pre-formatted commands for Rythm, and a little bit of clipboard interation to copy those commands to Discord with a single click.

我们一直在使用Discrord bot Rythm在游戏过程中播放背景音乐,因此实时管理音频是游戏管理员的职责之一。 DM也必须是DJ,har har。 这将是我的机会–一个简单的Web工具,可以自动运行Rythm Bot。 只需要一点点字符串操作就可以为Rythm生成预格式化的命令,还需要一点剪贴板插入操作,只需单击一下即可将这些命令复制到Discord。

I named the project the Marvelous Musical Automat — An automat, rather than a jukebox or a player, because it wouldn’t play the tracks, it would merely serve them up to the user with a single click, the way an automat serves food.

我将该项目命名为Marvelous Musical Automat(自动音乐机),它是自动机,而不是自动点唱机或播放器,因为它不会播放曲目,只需单击即可将曲目提供给用户,就像自动机提供食物一样。

My intentions were good, but good intentions don’t fix bugs. And they certainly don’t fix amateurism.

我的意图很好,但是好的意图不能解决错误。 而且他们当然不能解决业余问题。

科学怪人 (The Frankenstack)

To be effective, the Automat would have to store data, and it would have to store data long term. But when I was building, I had no idea what a development stack was, no idea what Mongo or SQL were. I had no idea how to connect a front end to a database. So I improvised.

为了有效,自动垫将必须存储数据,并且必须长期存储数据。 但是在构建时,我不知道什么是开发堆栈,也不知道什么是Mongo或SQL。 我不知道如何将前端连接到数据库。 所以我即兴创作。

Instead of a proper database, I would create a system that took all the data the system needed, and compress it into a single JSON object. The app would take that singular object, shove it into the browser’s local storage, and call it a day.

我将创建一个系统来获取系统所需的所有数据,然后将其压缩为一个JSON对象 ,而不是一个合适的数据库。 该应用程序将采用该单一对象,将其推送到浏览器的本地存储中,然后将其命名为“一天”。

And of course, the contect of the page would have to change based on what data was retrieved, so I’d also need a system that took that gigantic JSON object and parsed its contents into usable HTML.

当然,必须根据检索到的数据来更改页面的位置,所以我还需要一个系统,该系统采用该巨大的JSON对象并将其内容解析为可用HTML。

I had created an ersatz backend database and hooked it up to an ersatz React. A few nightmarish all-nighters later, I made it work.

我创建了一个ersatz后端数据库,并将其连接到ersatz React。 几个噩梦通宵达旦,我让它工作了。

在引擎盖下看 (Looking under the hood)

The core of the system consisted of two classes: Jukebox and Track. A Track consisted of a title, genre, and url. The system only held one Jukebox, and it consisted of a list of all the Tracks, in a single array, and a list of ‘genres’. The genres were the general categories the songs would be sorted into.

系统的核心包括两个类:点唱机和跟踪。 曲目由标题,流派和网址组成。 该系统仅容纳一个自动点唱机,它由单个轨道中的所有曲目列表和“流派”列表组成。 流派是歌曲将被分类到的一般类别。

There was almost no hard-coded HTML on the page, all of it was generated via JQuery based on information contained in the Jukebox object. Most of that JQuery witchcraft was handled by the methods of the Jukebox and Track classes. Of course, an object stored in JSON is just a plain object. No methods. So every time the page loaded, the Automat would reconstruct the Jukebox and all the Tracks from scratch.

页面上几乎没有硬编码HTML,所有这些都是通过JQuery基于Jukebox对象中包含的信息生成的。 大多数JQuery巫术都是由Jukebox和Track类的方法处理的。 当然,存储在JSON中的对象只是一个普通对象。 没有办法 因此,每次加载页面时,自动机都会从头开始重建自动存储塔和所有曲目。

[Lines 459–481]

[第459-481行]

This left the app with an unorganized pile of Track objects. I wanted the app to group the Tracks into genres, and then display those genres as separate categories on the page. At first glance it seems like it might have been wiser to give the Jukebox a series of Genre objects, each of which had a sub-list of Track objects, but at the time it seemed like that would have made it harder to create and delete genres on the fly. Instead, I had set it up so that the list of genres would be re-generated every time a track was added or deleted, by reading the indiviudal ‘genre’ tag on each Track.

这给应用程序留下了无序的Track对象堆。 我希望该应用将“曲目”分组为流派,然后在页面上将这些流派显示为单独的类别。 乍一看,为自动存储塔提供一系列流派对象似乎比较明智,每个流派对象都有一个Track对象的子列表,但当时看来那样会使创建和删除操作变得更加困难流派的流派。 相反,我进行了设置,以使每次添加或删除曲目时都可以通过读取每个曲目上的“ genre”标签来重新生成类别列表

When the genres were established, the process of building the page began.

建立体裁后,便开始了构建页面的过程。

//this function will execute when the body element loads
const buildPage = () =>{
    //record visibility status of genre boxes
    saveVisMemory();
    //delte old track listing, if any exists
    $('.allTracks').remove();
    const thisPage = document.getElementsByTagName('body')[0];
    thisPage.appendChild(jukebox.parseJukebox());
//[a lot of other stuff not relevant to this article....]
}

The global function buildPage did the whole thing. It would call three other methods, nested inside each other: Jukebox.parseJukebox, Jukebox.parseGenre, and Track.parseTrack. They would run in nested loops, creating a hierarchial tree of DOM elements via JQuery.

全局函数buildPage完成了整个任务。 它将调用彼此嵌套的其他三个方法:Jukebox.parseJukebox,Jukebox.parseGenre和Track.parseTrack。 它们将在嵌套循环中运行,并通过JQuery创建DOM元素的层次树。

//this is the big one. this writes the entire content of the HTML page.
    parseJukebox(){
        //create the space that all the genreBoxes will occupy.
        let allTracks = document.createElement('div');
        allTracks.classList.add("allTracks");


        let genreBox;
        
        //for each genre in this Jukebox...
        for(let i=0; i< this.genreList.length; i++){
            //get a box of all songs with that genre tag
            genreBox = this.parseGenre(i);
            //and add it to the big list
            allTracks.appendChild(genreBox);
        }
        //when this is complete, allTracks contains, per genre
        //a div element whose child nodes are all div elements
        //representing title cards for each song in said genre
        return allTracks;
    }
//creates a flexbox which contains a title card for every single track in a genre,
    //parameter n represents the index of the genre within the genreList.
    parseGenre(n){
        //create the outer box
        const genreBox = document.createElement('div');
        genreBox.classList.add('genre-box');
        //create the genre title text
        const genreTitle = document.createElement('h3');
        genreTitle.classList.add('genre-title');
        genreTitle.innerText = titleStyling(this.genreList[n]);
        //stick the title into the outer box
        genreBox.appendChild(genreTitle)
        //generate the inner box to hold the title cards
        const innerBox = document.createElement('div');
        innerBox.classList.add('inner-box');
        //give it a unqiue ID corresponding to the genre name
        let idTag = `${codeStyling(this.genreList[n])}-box`
        console.log(idTag)
        innerBox.setAttribute("id",idTag)
        //give the title element the ability to hide the box when clicked
        genreTitle.setAttribute("onclick","hideBox('"+idTag+"')")


        //make a title card out of each song that matches this genre
        //and stick each title card in the inner box


        let titleCard;


        //for each Track in this Jukebox...
        for(let i = 0; i<this.songList.length; i++){
            //if the Track's genre matches the argument passed to this function...
            if(this.songList[i].genre.toLowerCase()===this.genreList[n].toLowerCase()){
                //create a div element for its title card
                titleCard = this.songList[i].parseTrack(i);
                //and shove it into the genre box
                innerBox.appendChild(titleCard);
            } else {
                //console.log("rejected song:")
                //console.log(this.songList[i])
            }
        }
        
        //put the inner box inside the outer box!
        genreBox.appendChild(innerBox);
        //genreBox now contains a title heading for the name of the genre
        //and a titleCard for each song in the genre
        return genreBox;
    }
//returns html for building title card and button for the Track
    //parameter n represents this Track's place in the Jukebox's songList
    parseTrack(n) {
        let titleCard = document.createElement('div');
        titleCard.classList.add("title-card");
        titleCard.innerHTML=`<div class="tc-sub-box">
            <h2 class=\'song-title\'>${this.title}</h2>
            <button class="deleteButton" onclick="deleteTrack(${n})">DELETE</button>
            </div>
            <button class="selectButton" onclick=\'jukebox.select(${n})\'>${buttonImg}</button>`;
        return titleCard;
    }

With these tree methods working in unison, a page was miraculously created. From a database that could only store one hard-coded type of data, and only retrieve and display it in a single hard-coded way.

这些树方法协同工作,奇迹般地创建了一个页面。 从只能存储一种硬编码类型的数据,并且只能以一种硬编码方式检索和显示的数据。

None the less I’m happy for the experience. Not so much because it taught me what not to do, but because, oh my god, I actually saw this insane plan through to completion, and as a complete beginner.

尽管如此,我对这次体验感到高兴。 并不是因为它教会了我不要做什么,而是因为,天哪,我实际上看到了这个疯狂的计划,直到完成为止,而且是一个完整的初学者。

Soon I’ll be writing a follow-up to this post, detailing how I remade this project from the ground up using the MERN stack, and ran into a whole host of other problems.

很快,我将写这篇文章的后续文章,详细介绍我如何使用MERN堆栈从头开始重新构建这个项目,以及遇到很多其他问题。

翻译自: https://medium.com/@jrmartinez3d/a-little-javascript-knowledge-is-a-dangerous-thing-part-1-234e57bf28cb

javascript知识点

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值