Skip to content

Instantly share code, notes, and snippets.

@cameronwlewis
Created March 26, 2017 00:13
Show Gist options
  • Save cameronwlewis/3f7fcca22762dc68aab005819a3ca5c9 to your computer and use it in GitHub Desktop.
Save cameronwlewis/3f7fcca22762dc68aab005819a3ca5c9 to your computer and use it in GitHub Desktop.

[up vote]( "This question shows research effort; it is useful and clear")94[down vote]( "This question does not show any research effort; it is unclear or not useful")favorite

34

XMLHttpRequest has 5 readyStates, and I only use 1 of them (the last one, 4).

What are the others for, and what practical applications can I use them in?

javascript ajax xmlhttprequest readystate

shareimprove this question

edited Aug 10 '13 at 15:15

[

](http://stackoverflow.com/users/759866/benjamin)

Benjamin

11.8k1696179

asked Mar 11 '09 at 0:03

[

](http://stackoverflow.com/users/1585/marius)

Marius

36.9k18102128

[add a comment]( "Use comments to ask for more information or suggest improvements. Avoid answering questions in comments.")

4 Answers

activeoldestvotes

[up vote]( "This answer is useful")144[down vote]( "This answer is not useful")accepted

The full list of readyState values is:

State Description 0 The request is not initialized 1 The request has been set up 2 The request has been sent 3 The request is in process 4 The request is complete

(from http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp)

In practice you almost never use any of them except for 4.

Some XMLHttpRequest implementations may let you see partially received responses in responseText when readyState==3, but this isn't universally supported and shouldn't be relied upon.

here’s an example from when I ALMOST used one for myself. Yanked it from somewhere online. Not sure where.

##HTML side

<!DOCTYPE html>
<html>
<head>
    <title>Luscious Lobster</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
    <style type="text/css">
        #logo {
            max-width: 18%;
            display: block;
            margin: auto;
            padding:1%;
        }
    </style>
</head>
<body>
<img id="logo" src="lobster_logo.jpg">
<div id="nav">
    <div id="nav_wrapper">
        <ul>
            <li><a href="Week07.html">Home</a></li>
            <li><a href="Shop.html">Shop</a>
                <ul>
                    <li><a href="#">Lobster #1</a></li>
                    <li><a href="#">Lobster #2</a></li>
                    <li><a href="#">Lobster #3</a></li>
                    <li><a href="#">See All</a></li>
                </ul>
            </li>

            <li><a href="#">Cart</a>
            </li>
        </ul>
    </div>
    <!-- Nav wrapper end -->
</div>
<!-- Nav end -->
</body>
</html>

##CSS side

body {
   padding: 0;
   margin: 0;
   font-family: Arial;
   font-size: 17px;
   display: block;
}
 #nav {
   background-color: #141c5b;
   margin-top: 15px 
}
 #nav_wrapper {
   width: 960px;
   margin: 0 auto;
   text-align: center;
}
 #nav ul {
   list-style-type: none;
   padding: 0;
   margin: 0;
   position: relative;
   min-width: 200px;
   display:inline-block;
}
 #nav ul li {
   display: inline-block;
}
 #nav ul li:hover {
   background-color: #1d2e9f;
}
 #nav ul li a, visited {
   color: white;
   display: block;
   padding: 15px;
   text-decoration: none;
}
 #nav ul li:hover ul {
   display: block;
}
 #nav ul ul {
   display: none;
   position: absolute;
   background-color: #1d2e9f;
   border-top: 0;
   margin-left: -5px;
}
 #nav ul ul li {
   display: block;
}
 #nav ul ul li a:hover {
   background-color: #141c5b;
}

#From email from Bro. Bradshaw

Things to Check

  • Did you use the HTML5 doctype?
  • Did you exclude a base tag?
  • Did you use only relative links/urls?
  • Did you set your permissions correctly?
  • Did you check your assignment over an SSH tunnel?

SSH into the Linux Lab

Read "Welcome - Linux Lab Setup” under "Welcome" which has information about how to ssh into the server. If you have not logged into the Linux Lab before, your username is the same as used for www.byui.edu, but all lowercase. Your password may be: the default password Temple4dpc, the first eight characters of your email address, or the password you used last semester.

To change passwords on the Linux Lab Servers

  • In a terminal/console window, type in the command: yppasswd
  • Enter the old and new passwords; nothing will display as you type, not even ***
  • Do not use the numbers on the number keypad to enter numbers
  • Please use a secure password; the first 8 characters should not be a dictionary word

Create Default Directories and Files Once you can successfully log into the server you will want to read "Week 02 - Ponder : Web Page” which has information about how to set up your directory.

Permissions 711 - root directory (drwx--x--x) 755 - all directories under root (drwxr-xr-x) 644 - all files (-rw-r--r--)

##Use chmod -R to change all files and folders at once! You need to be outside of the directory, and use it right on the directory. The -R makes it recursive.

If you are familiar with Linux and bash you should be able to follow the instructions easily. But for those who are new, here are the steps I took while following the instructions.

#ssh into the server (replace allredjo) ssh allredjo@157.201.194.201 -p 215

#make sure you are in the root directory pwd #set the permissions on the root directory chmod 711 . (USE THAT PERIOD AT THE END RIGHT THERE) #create the public_html directory mkdir public_html #set the permissions on this directory chmod 755 public_html #change to the public_html directory cd public_html

#create index.html using nano nano index.html #write the html into index.html #edit file then save and close (cmd-o and cmd-x)

#OR create index.html using vi vi index.html #enter text mode by pressing i #write the html into index.html #exit text mode by clicking esc #save the file and exit vi by pressing ZZ

#OR create index.html using some other text editor such as emacs

#OR create the index.html file on your computer and upload it via SFTP

#set permissions on the file chmod 644 index.html #check the permissions to make sure they are correct ls -al #make all the week directories mkdir week{02..13} #set the permissions on all the week directories chmod 755 $(find . -type d) #copy index.html into all the directories echo week* | xargs -n 1 cp index.html #set the permission on all the files just copied find . -type f -print | xargs chmod 644

Create your Home Page

Now follow the instructions to modify index.html to have a link to the index.html file in each folder. I recommend using an SSH FTP tool, such as Cyberduck on the Mac, to SFTP into your directory so you can create your HTML files on your desktop and then SFTP them to the server. You will need to set the permissions on your files when you are done.

Note 0: The work this week, and throughout the remainder of the semester, is mean to be done by hand. Do NOT use third party libraries like jQuery, bootstrap, foundation, etc.

Note 1: Please use HTML5 syntax instead of the older HTML4 or XHTML syntax. The main thing you need to do is use the HTML5 doctype <!DOCTYPE html> instead of the older XHTML doctype <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN” "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"\>

Note 2: Since I am not on campus I have to create an SSH tunnel into the network to grade your assignments. Using a base tag makes it so that I cannot grade your assignments. Do NOT use a base tag (even thought the instructions specify that you should).

Note 3: Also, since I am grading over an SSH Tunnel you MUST NOT use absolute links since I will not be able to grade your assignment if you do. This applies not just to this assignment, but to every assignment this semester. Do NOT use absolute links such as <a href=“http://157.201.194.254/~bradshawr/week02/index.html”\>Week 02</a> Instead use relative links such as <a href=“week02/index.html”>Week 02</a> If you need to create a relative link to a file higher up than your current file you should use “../“ for every level you need to go up. For instance, if you are in the week02/index.html file and you want to create a link to your home page in the folder above week02 your relative url would look like <a href=“../index.html”>Home Page</a>. If you wanted to go up two levels you would use "../../“.

Note 4: Do NOT use spaces in any file or directory names. Again, doing so makes grading very difficult for me.

Note 5: The instructions state that you must validate the page. Due to the nature of HTML5, there is not a good HTML5 validator. So, you do not have to validate your page. If you want to try to find an online HTML5 validator you are welcome to do so, but you do not need to put a logo on the page.

Be sure you follow the instructions. When I grade your home page I will check to see:

  • Does each link work?
  • Are the links centered?
  • Is there a title?
  • Is there heading text?
  • Are all links present?
  • Are the links in a <ul><li> structure?
  • Are the links relative instead of absolute?
  • Is there NO base tag?
  • Are you using the HTML5 doctype?

Setup SSH Tunnel

Next you will want to try viewing your index.html file in a browser and make sure you can click on all the links to make sure everything is set up correctly.

If you are on the BYU-I network you can just go to http://157.201.194.254/~bradshawr/index.html (replace bradshawr).

If you are not on-campus using the BYU-I network then you need to create a secure connection between your local computer and the Linux Lab so that requests from your browser will go thru. We do this using SSH Tunneling (also called SSH Port Forwarding).

Even if you do have access to the BYU-I network I would still recommend that you learn how to set up an SSH tunnel off the BYU-I network. You will want to make sure your assignments work correctly when accessed via an SSH tunnel since that is how I will be grading them.

The following information is specific to Linux, but it has some good general information about SSH Tunnels (port forwarding) if you are not familiar with the concept. https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding

Mac/OSX, Linux, or any other Unix-variant Open your command line interface (Terminal) and enter (replacing bradshawr with your ID): sudo ssh -L 80:157.201.194.254:80 -p 215 -l bradshawr -N 157.201.194.202 You will need to enter your desktop password and then your Linux Lab password. The ssh tunnel should be established if you no longer have a command prompt and there are no error messages. You might see a gray rectangle. Now you can go to your browser and enter the URL http://localhost/~bradshawr/index.html (replacing bradshawr with your ID).

Windows Download plink.exe from http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html Move plink.exe from where you downloaded it to C:\Windows (or any other folder that is in your PATH). Open your Command Prompt window and enter (replacing bradshawr with your ID): plink -ssh -L 80:157.201.194.254:80 -P 215 -l bradshawr -N 157.201.194.202 You will need to enter your Linux Lab password. The ssh tunnel should be established if you no longer have a command prompt and there are no error messages. You might see a blinking underscore. Now you can go to your browser and enter the URL http://localhost/~bradshawr/index.html (replacing bradshawr with your ID).

Notes:

  • This needs to be entered on your local desktop machine. Sometimes students will SSH into the Linux Lab and then try to create the SSH Tunnel there. That will not work.
  • If you are having trouble, it is possible that port 80 is already in use on your computer. If you run into any trouble establishing a connection try replacing 80:157.201.194.254:80 with 8080:157.201.194.254:80 Then in your browser enter the URL http://localhost:8080/~bradshawr/index.html (replacing bradshawr with your ID).
  • If you are still having trouble, it is possible that port 8080 is already in use on your computer. You can use any unused port number between 1025 and 49150. For example, you could use 7685:157.201.194.254:80 Then in your browser enter the URL http://localhost:7685/~bradshawr/index.html (replacing bradshawr with your ID).
  • If you are still having trouble, it is possible that the 157.201.194.202 server is down. Try using 157.201.194.203 or 157.201.194.204.
  • If you are still having trouble, there may be a VPN/firewall/other issue that is preventing the connection. Try establishing the tunnel on another network to see if it works there.
  • If you are still having trouble, try SSHing into the Linux Lab to make sure it is online. If the Linux Lab is down for maintenance then you will not be able to establish an SSH Tunnel.
  • If you are still having trouble please contact the instructor.

If you are on Windows and you would like to use PuTTY to setup an SSH Tunnel there are some instructions here: http://emp.byui.edu/ercanbracks/cs213/Tunneling.htm

Note 0: If you are using Windows and you already have PuTTY installed, you might need to update to the latest version.

Note 1: If you are using Windows, make sure IIS is not running since it uses port 80 by default. IIS runs automatically on Windows 10 and perhaps on earlier versions of Windows as well. Or you could leave IIS running and use a different port in PuTTY such as 7007.

Note 2: If it still doesn’t work then even if you don’t think IIS is running on your machine try using a different port such as 7007.

As I was reading the textbook regarding parameters (4.9.3, pg 174) I found myself reading and re-reading the same few sentences, which said:

When a function is called, the values of the actual parameters specified in the call are, in effect, copied into their corresponding formal parameters, which behave exactly like local variables. Because references are passed as the actual parameters of objects, the called function has access to the objects and can change them, thereby providing the semantics of pass-by-reference parameters.

Looking back, these two sentences probably could have been phrased a lot better, because what it sounds like this is saying is two contradictory statements:

  1. When parameters are passed to a function, it's only a copy of the value instead of a reference.
  2. When parameters are passed to a function, the function can change stuff by reference.

That was a little confusing for me. But I think I figured it out.

What I missed was the fact that it mentioned objects. An object in JS is something like this:

var person = {

firstName:"John",

lastName:"Doe",

age:50,

eyeColor:"blue"

};

The object is person, and the properties are firstName, lastName, age and eyeColor. The values of these properties are (respectively) "John", "Doe", "50" and "blue". When you pass a property value to a function, it is only a copy of the value, not a reference to the value. This part is different from C++ because you can’t use the & operator to pass the value by reference.

However!

If you pass an object to a function, like person, you CAN access the property values by reference, like this:

person.lastName

or

person["lastName"]

**

Cool right?

#Don’t even bother using another IDE. Just don’t. Seriously.

Alright. So here we are. After probably oooooh 12-15 hours, I think I finally have this figured out. Here are some things I'm going to cover:

  • My thoughts on IDEs/editors for JS
  • My thoughts on JavaScript frameworks
  • npm
  • WebStorm
  • Babel & ES6
  • Facebook's Flow language
  • How to set it ALL up in WebStorm

##My thoughts on IDEs/editors for JS OK, I've seen a lot of resources, and they all seem to make a LOT of assumptions about how to accomplish all this.

In fact, that's why right out of the gate, WebStorm is the best tool for JS for the forseeable future, because the amount of configuration for other text editors to enable the same usability and feature set are not only out of control in terms of difficulty, but just downright don't work. The extensions in other apps to enable the same supposed functionality I'm looking for have a staggering amount of bugs and silly workarounds that just kill it for me.

Editors I've tried:

  • Atom: Buggy extensions. No "IntelliSense"-like linting/parsing of code. No debugging support.
  • VS Code: Seems really, really promising, but just isn't there with support for lots of frameworks and libraries. Babel implementation is zilch. Horrible, horrible setup for debugging, and every extension has literally buttloads of text-based and terminal-based setup for preferences and settings.
  • Sublime Text: Tempting cuz of how simple it is, but it's losing support and the extensions and plugins it DOES have are even more difficult to set up than VS Code or Atom. Also, it's a little clunky to use. Not open source either.
  • CodeRunner: Literally just for running code (if that). And it costs $15-$20. No extensions/plugins that I know of.
  • Coda: $99 with no discounts I've been able to find with a couple hours of searching. No student discount either. And there's probably only like 20 plugins/extensions available. Absolutely no support for Babel or like...anything else new and cool. Seems really nice and "whooshy" to use, but just...yeah.

Don't reinvent the wheel, Cameron. Seriously.

##My thoughts on JavaScript frameworks

There is a lot of battling going on out there about whether frameworks are a waste of time and compromise the very productivity gains they're supposed to bring. At first I held on to this wholeheartedly (read a lot of sources), and I can certainly see where they're coming from. It causes a lot of splintering among the JS community. And brings extra layers of abstraction, and many of these frameworks/libraries die out and become disused, lacking updates from their creators. What then, of all the time you spent learning them?

Anyway, but I've come to the conclusion that some frameworks/libraries really are worth using, especially if they're created by a large company that has thrown it's support behind it, and if it really does bring productivity gains to its users. But it doesn't seem smart to be an early adopter of a lot of these technologies. Many of them die out, and you've just wasted a lot of time.

For now though, the frameworks/libraries that seem really worth using as of now are:

  • Node.js (for SURE).
  • React.js
  • Flow

##Working Guide on How to set up Babel, Flow, ESLint and other stuff in Webstorm

###First, you gotta npm like crazy for a few minutes (or do it all at once!). This is how you do it.

  • Edit: before anything else, create a .git folder at the project root with Github Desktop.

  • Navigate to your project folder in Finder.

  • Right-click on the project folder, go to 'Services-> New Terminal at Folder'. If you don't see that, know that it can be done. Google it, cuz it's really rad.

  • type npm init. Go through the menu prompts (doesn't really matter much). We need this to happen because it creates a package.json in the project root and because it creates a node-modules folder with all the fun stuff we want to use in our WebStorm projects.

  • Now you can install all the rest of the stuff you want with one command, like this: -

  • npm install --save-dev babel-cli babel-preset-latest eslint babel-eslint .....yadda yadda.

  • Or one at a time, each with npm install --save-dev in the front, followed by the npm package.

  • (the --save-dev writes each package name and its "dependency" [don't understand that yet] to the package.json file we created, aaannnd that's important for some reason.

The names of the packages you want are: (they're all listed here too: http://babeljs.io/docs/plugins/)

  • For Babel:

  • babel-cli installs Babel

  • babel-preset-latest preset to transpile the latest/most-recent JS abilities to ES5

  • babel-eslint uses Babel to lint stuff instead of ESlint, which is good cuz Babel knows more

  • For Flow:

  • flow-bin

  • For Babel transpiling of Flow:

  • babel-plugin-flow-syntax (well this is handy for other stuff actually)

  • babel-plugin-transform-flow-comments to turn Flow types into comments

    • OR use babel-plugin-transform-flow-strip-types to strip Flow stuff altogether.
  • For ESLint:

    • eslint to make sure we don't mess up in Webstorm
    • eslint-plugin-flowtype to make sure flow is linted correctly by eslint

    Here's all of that in one chunk for you to copy/paste in the future:

npm install --save-dev babel-cli babel-preset-latest babel-eslint flow-bin babel-plugin-syntax-flow babel-plugin-transform-flow-comments eslint eslint-plugin-flowtype

###Next, we're gonna do some more terminal stuff. Order doesn't matter.

  • In the same terminal, type flow init to initialize Flow via the .flowconfig file it creates. Don't worry, the command worked. If nothing spat out at you, you're good.

  • Then, type eslint --init. This will initialize ESLint and create it's config file. A little menu will come up. You should probably just choose the first option to decide on everything for yourself.

  • We DO want JSX, and we DO want semicolons. And we DO want JSON (actually I don't know, but I think it could only help given the issues I've been having. Honestly it probably doesn't matter).

###Ok! Now we gotta make some files. For the record, ##DO NOT create these create these files in TextEdit, or Textastic, or Sublime (tested these), or Atom, or VS Code (haven't tested these). For some reason, these all create characters in the file (like "\n") that cause bugs later when the settings are being parsed by Babel. Just don't do it.

(I just figured out why! It's technically a JSON-type file, so anything that can recognize JSON is probably good, BUT STILL YOU SHOULD USE WEBSTORM.)

###Instead! Open your project now in Webstorm.

  • Create a new file entitled .babelrc. This is our config file for Babel.
  • Now put in the preset and plugins you want in the following format:
{
  "presets": ["latest"],
  "plugins": ["syntax-flow", "transform-flow-comments"]
}

(see https://babeljs.io/docs/plugins/#plugin-preset-paths for more details.)

  • Lastly, open .eslintrc.json in WebStorm and just put this at the very top to have Babel do the parsing through ESLint--otherwise we're gonna get a bunch of dumb Flow-related errors. Paste this over everything else in the file:
{
  "parser": "babel-eslint",
  "plugins": [
    "flowtype"
  ],
  "rules": {
    "flowtype/boolean-style": [
      2,
      "boolean"
    ],
    "flowtype/define-flow-type": 1,
    "flowtype/delimiter-dangle": [
      2,
      "never"
    ],
    "flowtype/generic-spacing": [
      2,
      "never"
    ],
    "flowtype/no-primitive-constructor-types": 2,
    "flowtype/no-weak-types": 2,
    "flowtype/object-type-delimiter": [
      2,
      "comma"
    ],
    "flowtype/require-parameter-type": 2,
    "flowtype/require-return-type": [
      2,
      "always",
      {
        "annotateUndefined": "never"
      }
    ],
    "flowtype/require-valid-file-annotation": 2,
    "flowtype/semi": [
      2,
      "always"
    ],
    "flowtype/space-after-type-colon": [
      2,
      "always"
    ],
    "flowtype/space-before-generic-bracket": [
      2,
      "never"
    ],
    "flowtype/space-before-type-colon": [
      2,
      "never"
    ],
    "flowtype/type-id-match": [
      2,
      "^([A-Z][a-z0-9]+)+Type$"
    ],
    "flowtype/union-intersection-spacing": [
      2,
      "always"
    ],
    "flowtype/use-flow-type": 1,
    "flowtype/valid-syntax": 1
  },
  "settings": {
    "flowtype": {
      "onlyFilesWithFlowAnnotation": false
    }
  }
}

Shareable configurations


Recommended

This plugin exports a recommended configuration that enforces Flow type good practices.

To enable this configuration use the extends property in your .eslintrc config file:

{
  "extends": [
    "plugin:flowtype/recommended"
  ],
  "plugins": [
    "flowtype"
  ]
}
See ESLint documentation for more information about extending configuration files.


Settings


onlyFilesWithFlowAnnotation

When true, only checks files with a @flow annotation in the first comment.

{
  "settings": {
    "flowtype": {
      "onlyFilesWithFlowAnnotation": true
    }
  }
}

###Now open the WebStorm preferences, under 'WebStorm-> Preferences'.

  • Under Languages & Frameworks, click JavaScript, then choose ‘Flow’ as the language.
  • Put in the Flow executable in the node_modules folder in our project.
  • Its in node_modules-> .bin -> flow.
    • Also if you can't see .bin in the file finder window, just press Shift-CMD-'.' at the same time (that's the period button btw) and it'll show up. You relaly gotta press it at the same time. Keep trying.
  • Afterwards you most likely wanna check every checkbox in that window. Makes Flow a lot more handy.
  • Alright, now under Languages & Frameworks -> JavaScript, click on Code Quality Tools, then ESLint.
  • For Node Interpreter, you want node_modules/babel-cli/bin/babel-node.js
  • Npm package, node_modules/npm
  • ESLint package: node_modules/eslint
  • And for the config file, it should find it automatically like it says. if you have problems later, explicity specify it in this window.
  • And we're done!
  • Then go to Tools --> File Watchers. We're gonna set up Babel.
  • Click the + button to add.
  • I just want you to know, that this window is responsible for a lot of problems. If you don't get this right here, it will screw everything up later.
    • I have tried so many configurations for this window copied and pasted from the internet, but honestly the only thing that has worked is leaving it as-is, with the only possible change being in Arguments, replacing "es2015" with "latest". THAT IS IT.
    • For the program executable under "Program", use this at your project root: node_modules/.bin/babel
    • Also, put a check on "Immediate File Synchronization". Not sure what "Track only root files" does yet, or what it means.
  • And we're done with the settings! Yay!

##A few last things!

  • If you wanna use Flow, you have to put this at the top of your .js files:
// @flow
  • If you wanna debug, you need to MAKE SURE YOU DEBUG THE correct .js FILE IN the dist folder! You can make sure this is set up in the 'Run/Debug Configurations' dialog box in WebStorm.
  • LASTLY, in the 'Run/Debug Configurations' dialog, make sure the settings are using:
  • Node interpreter: node_modules/babel-cli/bin/babel-node.js
  • Node parameters: -r node_modules/babel-core/register
  • Working directory: your project root
  • JavaScript file: the matching one in your dist folder that was spit out by Babel!
  • Also, make sure you set up the 'Browser / Live Edit' function the way you want.
  • Put a check on 'with JavaScript debugger', too, in that window!
  • All done!

Other notes for the CamBam pasted from online:

Ordering matters for each visitor in the plugin.

This means if two transforms both visit the “Program” node, the transforms will run in either plugin or preset order.

  • Plugins run before Presets.
  • Plugin ordering is first to last.
  • Preset ordering is reversed (last to first).
"plugins": [
  "transform-decorators-legacy", // will run first
  "transform-class-properties" // will run second
]
**COPY**

Yes this is confusing, see babel/notes #2. I believe the reason why (for backwards compatability) is that most users had listed “es2015” first and “stage-0” second. stage-0 would run before es2015.

"presets": [
  "es2015", // will run third
  "react", // will run second
  "stage-2" // will run first
]
**COPY**

Plugins and Presets can both specify options. You can do so in your config by wrapping it in an array and providing a options object. For example:

{
  "plugins": [
    ["transform-async-to-module-method", {
      "module": "bluebird",
      "method": "coroutine"
    }]
  ]
}

// notice the wrapping array around the preset and option

{
  "presets": [
    ["es2015", { "loose": true, "modules": false }]
  ]
}
**COPY**

Please refer to the excellent babel-handbook to learn how to create your own plugins.

The simple plugin that reverses names (from the homepage):

export default function ({types: t}) {
  return {
    visitor: {
      Identifier(path) {
        let name = path.node.name;
        // reverse the name: JavaScript -\> tpircSavaJ
        path.node.name = name.split('').reverse().join('');
      }
    }
  };
}
**COPY**

To make your own preset, you just need to export a config.

// Presets can contain other presets, and plugins with options.
module.exports = {
  presets: [
    require('babel-preset-es2015'),
  ],
  plugins: [
    [require('babel-plugin-transform-es2015-template-literals'), { spec: true }],
    require('babel-plugin-transform-es3-member-expression-literals'),
  ],
};
**COPY**

For more info, check out the babel handbook section on presets or just look at the es2015 preset repo as an example.

OTHER NOTES:

4[down vote]( "This answer is not useful")accepted

babel-eslint is a parser that allows you to use ESLint with code that is supported by Babel (ES6+ features, flow types, etc.). ESLint on it's own only supports ES6, JSX and object rest/spread, anything beyond that requires babel-eslint. eslint-plugin-babel is a plugin that fixes/adds a few rules that work with ES7 and beyond features. eslint-plugin-react is a plugin that adds a bunch of rules specific to React applications.

Hey guys,

Not sure this plugin is needed anymore, since you can use as an eslint parser babel-eslint which now integrate much better with eslint. Also there is another eslint plugin that lints js files and fixes no-undef issues with Flowtypes( https://github.com/gajus/eslint-plugin-flowtype ). Please let me know if for some reason you can't use those 2.

###Tag vs element vs attribute vs property tags are <these> <things>. elements are what go in between <these> I'm an element <things> attributes are the stuff that goes inside <these like="this"> (see 'like'? That's an attribute). properties are the stuff in quotes.

HTML tags vs. elements vs. attributes

When talking (or writing) about HTML, it is common for many people to refer to just about everything as "tags" instead of using the proper terms: "tag", "element", and "attribute". A lot of the time what the author really means can be figured out by looking at the context, but sometimes it can be confusing.

Using the correct terminology is not very difficult. It will also make it easier for others to correctly interpret what you mean, not to mention lend more credibility to what you have to say. This is pretty basic knowledge, but in case you need to refresh your memory I've written a quick explanation of tags, elements, and attributes in HTML.

HTML elements

An element in HTML represents some kind of structure or semantics and generally consists of a start tag, content, and an end tag. The following is a paragraph element:

<p>
This is the content of the paragraph element.
</p>

HTML tags

Tags are used to mark up the start and end of an HTML element.

A start tag consists of an opening angle bracket (<) followed by the element name, zero or more space separated attribute/value pairs, and a closing angle bracket (>).

A start tag with no attributes:

<p>

A start tag with an attribute:

<p class="info">

End tags consist of an opening angle bracket followed by a forward slash, the element name, and a closing angle bracket:

</p>

There are also some elements that are empty, meaning that they only consist of a single tag and do not have any content. In HTML, such tags look just like opening tags:

<br>

The syntax is slightly different in XHTML. Empty elements must either have an end tag or the start tag must end with />. In order to ensure backward compatibility with HTML the most common way of writing empty elements in XHTML is to use minimised tag syntax with a space before the trailing />:

<br />

HTML attributes

An attribute defines a property for an element, consists of an attribute/value pair, and appears within the element's start tag. An element's start tag may contain any number of space separated attribute/value pairs.

The most popular misuse of the term "tag" is referring to alt attributes as "alt tags". There is no such thing in HTML. Alt is an attribute, not a tag.

<img src="foobar.gif" alt="A foo can be balanced on a bar by placing its fubar on the bar's foobar.">

Document sections

Another related term is "section". An HTML document is divided into a "head" section (the contents of the head element) and a "body" section (the contents of the body element).

Not nitpicking

You may call this nitpicking, but I don't think it is. Sure, most of the time people will understand what you mean even if you call everything a "tag". But by using the correct terminology you reduce the risk of being misunderstood, and you will sound more professional, so you really have nothing to lose by learning the difference.

##Instructions:

Create a new page describing what changes you made and your rationale. You do not need to make this site "fancy;" just create a <h1> tag for each change and describe the change in <p> tags. While this page must be valid HTML, it does not need to be styled.

Each part of your rationale needs to include:

  • Subject: Describe in a few words what part of the web site you are commenting on. This goes in the <h1> tag.
  • Guideline: Provide a link to the reading describing the principle of web design that you will be referencing in your analysis.
  • Rationale: Provide a paragraph describing why the example adheres to the guidelines.

At the top of this page, include a link to the improved commercial web site (the first part of the assignment).

##Grading:

Your program will be graded according to the following rubric:


Exceptional 100%Good 90%Acceptable 70%Developing 50%Missing 0%Presentation 40%Both the home page and the second page look fantasticAll of the guidelines are honoredThere are minor usability problems in one or both pagesThere are major usability problems in one or both pagesNo changes were made since Week 03Rationale 60%All the changes are perfectly described and the rationale is convincingAll the changes are adequately describedThere exists minor ambiguity in the rationale, some changes are not described, or some parts of the rationale are missingA flaw exists in the rational seriously impacting its usefulnessThe rationale is missing

##Notes on the changes I'm gonna make: -decided to split the gallery into 3 different pages, based on what I read regarding sequential or sequence site layout. Beneficial for site of this type (see what the actual terminology is, see webpage again)

-(must make these comments actually in the web pages…)

-Remove color border behind each photo to obtain greater graphical continuity and less fragmentation

####What are classes and ID and nested stuff in the stylesheet? What do they mean again? UGH I FORGOT

-make each and every page accessible and understandable to people who may have just dropped in from the internet

-put side navigation links on right side of EACH page for gallery and email signup in accordance with user’s typical interface expectations

-renamed “GALLERY” to CAMCREATE so that people dropping into the page know what website they’re on

##Teach One Another stuff

###instructions:

Teach One Another

  • This week you will not be working with your group.
  • The things students usually lose points on:
    • Not doing both parts of the assignment (by the end of the assignment you should have written 8 posts).
    • Indicating which post exhibits good or poor design. Do not do that.
    • Not including the subject, description, url, and screen shot in each of the 2 website posts.
    • Not including the subject, rationale, url, and screen shot in each of your 6 analysis posts.
    • Not including the screen shots in the post. Some students in the past have put their screen shots into Word documents and posted a link to their Word document. Do not do that.
    • Not writing an insightful analysis.

Analysis

The second part of the assignment is to analyze the sites of other students. You are to make specific references to how well (or poorly) the side adheres to the standards mentioned in the reading. You will do this by replying to the original thread. For each analysis, please do the following:

  • Subject: Describe in a few words what part of the web site you are commenting on.
  • Guideline: Provide a link to the reading describing the principle of web design that you will be referencing in your analysis.
  • Rationale: Provide a paragraph describing why the example adheres to the guidelines or why it does not.
  • Screen shot: Provide a small screen shot of the part of the design your rationale refers to.

You are to make six analysis posts, each for 15% of the grade. Note that, on average, each site will have three analysis replies. Clearly it will be much easier to offer the first reply rather than the last because the more obvious issue will probably be "claimed" early.

Grading

The grading for this activity will be the following:

Exceptional 100%Good 90%Acceptable 70%Developing 50%Missing 0%Two Sites 10%Both sites are outstanding examplesBoth sites have all the requirements: new thread, subject, description, link, and screen-shotOne aspect of one post is missing or not done wellOne post is "good enough" for an analysis to be completedMissingFirst analysis 15%Analysis is insightfulEverything is present and the analysis is correctOne aspect of the analysis is missingOne factual error is present in the analysisMissingSecond analysis 15%Analysis is insightfulEverything is present and the analysis is correctOne aspect of the analysis is missingOne factual error is present in the analysisMissingThird analysis 15%Analysis is insightfulEverything is present and the analysis is correctOne aspect of the analysis is missingOne factual error is present in the analysisMissingFourth analysis 15%Analysis is insightfulEverything is present and the analysis is correctOne aspect of the analysis is missingOne factual error is present in the analysisMissingFifth analysis 15%Analysis is insightfulEverything is present and the analysis is correctOne aspect of the analysis is missingOne factual error is present in the analysisMissingSixth analysis 15%Analysis is insightfulEverything is present and the analysis is correctOne aspect of the analysis is missingOne factual error is present in the analysisMissing

##Developer’s Forum post subjects:

  • Are semicolons really optional? (Pg 146 of text) Why does an IDE like WebStorm require them?

  • pg 174, bottom. Textbook is confusing: Does Javascript allow passing variables by reference or not?

I initially kept getting the first question in the quiz wrong because one of the correct choices was 'Semicolons are mostly optional in Javascript" or something like that, and I didn't check it. This was really confusing to me since the textbook didn't quite say it like that. It said:

*The safest way to organize JavaScript statements is to put each on its own line whenever possible and terminate each statement with a semicolon. *

Again, this was probably because I was reading it too quickly. What it's really saying is:

var i = 0; i++        // \<-- semicolon obligatory
                      // (but optional before newline)
var i = 0             // \<-- semicolon optional
    i++               // \<-- semicolon optional

It's also required after a parentheses/round bracket of an if, for, while, or switch statement, as follows:

if (0 === 1) /*do nothing*/ ; alert ("hi");

So are semicolons really optional?

respond to thread “getting the message to disappear”, maybe

maybe talk about things I learned regarding regex….interesting resources/discoveries/finds

Post #1 (a new thread)

Subject: good thing JS has regex!

Post:

After using regex for a bit this week and last week, it’s been easy to see the utility of regular expressions. They’re amazing! Parsing text and input has seriously never been easier!

It occurred to me that since JS doesn’t have variables statically-typed like in C++, it becomes even more important that all variable values are validated with regex before being processed by anything (like a function for example). There were several times when I didn’t have values validated with regex beforehand, which left me with a bug in my hands that I didn’t know about until that particular function was called/executed in my own live testing in a browswer.

On one hand, typing out code in JS is much easier and requires less code, because I can send any value to any function. I don’t have to create a bunch of overloaded functions each accepting a different data type (like in C++). But on the other hand, its quite a bit harder to debug when I don’t find the bugs

CS 213: 04 (Online); Fall 2016 - Announcements: Week 6 Posted Saturday, October 15, 2016 1:35 PM MDT

Welcome to Week 06 Cameron!

I know that learning a new programming language can be a challenge and for some of you this semester may seem like you are learning four. I hope you will post your questions as well as any insights you might have, that the whole class can grow together.

Regex

This week we will continue working with JavaScript. The main thing we will be working on this week is form validation using regular expressions (regex).

Some resources for regex include:

https://regex101.com/#javascript

http://regexone.com/

http://www.regexpal.com/

http://www.rexegg.com/

http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

http://eloquentjavascript.net/09_regexp.html

http://www.smashingmagazine.com/2009/06/essential-guide-to-regular-expressions-tools-tutorials-and-resources/

http://www.smashingmagazine.com/2009/05/introduction-to-advanced-regular-expression

Overview of This Week's Assignments

Prepare

  • The typical reading and quiz.
  • While you are reading the assigned material, you should take note of any questions you have that you can ask in the Teach One Another assignment.

Teach One Another

  • This assignment will be a whole class discussion like last week.
  • Based on past experience, many of you will have questions about JavaScript that will arise as you are working on the Ponder assignment. I would recommend starting on the Ponder assignment as early in the week as possible so that you can ask your questions of your fellow students.
  • Please remember to keep posting until you have 100 points.

Ponder

  • You will find a link to a file called Week06.html in the instructions for the assignment. Please use this file instead of trying to create your own (which students have done in the past to their detriment).
  • I have created a more up to date version of the Week06.html file. You can use either file, but my version is much simpler than the version linked from the instructions so you might find it easier to work with.
  • Your main task this week will be validating input elements.
  • You will need to create an external JavaScript file to hold your functions. Your JavaScript must go in an external JavaScript file.
  • Unlike last week, you will need to make changes to the HTML file. But, the changes you make do not involve changes to the HTML elements themselves, only to attributes of the HTML elements. For example, I have seen students that have added buttons to the HTML so that the validation check happens when the button is clicked. DO NOT DO THIS!
  • In order to validate the input elements you may be tempted to use an event on the input elements like onBlur. I would strongly recommend that you use onInput instead. This is what a professional web developer would use since it allows the user to see the validation occurring as they type.
  • Here is an example of how you might use onKeyUp, “this”, and class to accomplish the task:
    • <input onKeyUp="validateAge(this.value, 'age1');" size="3"/>
    • <span class='age1' style='color:red'>Invalid age</span>
    • Then in your external JavaScript file you might have a function that looks something like this:
    • function validateAge(theAge, theClass){
      • if(theAge >= 0 && theAge <= 118){
        • document.getElementsByClassName(theClass)[0].style.visibility = 'hidden';
      • }
    • }
  • Of course there is a lot more that needs to be done to the JavaScript function to complete the exercise, but this should give you a hint of how you could accomplish the assignment without adding HTML elements while making your JavaScript functions generic as required.
  • For problem #1, I will be checking for ages less than 0, greater than 118, and ages that are not a number.
  • For problem #2, I will be checking that the SSN is in the format 000-00-0000. I will be checking that 000000000 does not work. I will be checking that the correct format works with white space both before and/or after it.
  • For problem #3, I will be checking the credit card number both with and without internal spaces. I will be checking that both formats work with white space both before and/or after it.
  • For problem #4, I will be testing with dates such as 1/1/2015, 12/12/2015, 13/1/2015, 1/33/2015, 1/1/2101, etc. with white space both before and/or after them.
  • For problem #5, I will test a number of common US state abbreviations. I will be checking that uppercase, but no lowercase, is accepted. I will be checking that the correct format works with white space both before and/or after it.
  • For problem #6, I will be testing with money amounts such as $1; 1.; 1.0; 1.00; $1.00; 1,000; 1000; 1,00; etc. I will be checking that the correct format works with white space both before and/or after it.
  • Make sure your file permissions are set correctly after you upload the two files to your week06 directory.

One final note, you will notice that currently the HTML in the file in the instructions is using tables for layout:

<table> <tbody> <tr> <td> <input size="3"> </td> <td> <span style="color:red">Invalid age</span> </td> </tr> <tr> <td> <input size="3"> </td> <td> <span style="color:red">Invalid age</span> </td> </tr> </tbody> </table>

Please, do not do this. Many years ago, before CSS matured, tables were often used for layout like this. This is now considered a worst-practice. This could just as easily been done with divs.

<div> <input size="3"> <span style="color:red">Invalid age</span> </div> <div> <input size="3"> <span style="color:red">Invalid age</span> </div>

Attachments:

week06.html

CS 213: 04 (Online); Fall 2016Go to Announcements >>

You are receiving this message because you subscribed to receive instant notifications via email. Change Notification Settings

How do I get text over to the .js side of things?

I can’t use a button….. I need to pass it to a function. But where?

How did the last assignment do it?

Lemme look.

Alright. Thy used a button tag. Ah yes. And then they used onclick. That is called an "event". I need to find an event that will get angry at the user when the user does not have an actual number in the input box for Age.

  • I think that event will be onchange: "The input element is changed and loses focus."
  • the tag to use this with should be either <input> or <textarea>.

Test em out.

AHAH! See this from w3schools regarding the onchange event:

Example

Execute a JavaScript when a user changes the selected option of a <select> element:

<select onchange="myFunction()">

SO BASICALLY.... I should send the inputted text to a JavaScript function to have it validated WHEN onchange is tripped/activated/whatever.

To validate it, I should see if there's a JS-built-in isnum function (something similar) like there is in C++.

#YOU CAN'T FREAKING REFERENCE THE SAME ELEMENT NAME IF IT'S A DUPLICATE. WOW I FEEL LIKE I LEARNED A REALLY TIME-CONSUMING LESSON. GOSH DANGIT.

####WHEN YOU WAKE UP, CHECK THESE OUT:

Attachment from developer’s forum:

validate.JPG

And then this:

More Examples

Example

Execute a JavaScript when the user changes the content of an input field:

<input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">

##Okay. Problem # 2 now.

#2 Social Security Number

Write the HTML and JavaScript to prompt the user for a SSN. Initially, the field will be blank and a message will appear next to the input field indicating that a valid SSN has not been presented. When the user types a valid SSN (000-00-0000), then the error message will disappear.

The SSN must be the only thing in the input field. There should be nothing but white spaces before or after the SSN.

How should I accomplish this one? Nothing but white spaces????? Typo, or true?

#4 Date

Having issues with this one.

Btw, this regex:

(^1[0-2])|(^[0-9]) works for entering the month, unless you enter 12 or above. DOH.

Same here: (\d*)

(^[0-9][0-2])*(^[0-9])

\d+\W\w\S+

##Post 1 ###How to set up a transpiler Hey everyone, after going through a several tutorials about how to get this set up, I’ve decided to share what I've learned with you all.

So at this point I'm sure many of you are familiar with a few text editors or IDEs that are handy for HTML/CSS and JavaScript, and this setup will work with practically any of them. It begins (sadly!) at the command line.

These instructions should work on either Windows or Mac (though I did it on a Mac), because the installation uses npm, or the "Node Package Manager". It helps manage and install packages made with Node.js. Unfortunately I don't have instructions on installing npm, but they should be pretty easy to find a guide for that online.

After installing npm, you need to navigate to your project folder you'd like to manage, using cd or some other method in the command line.

Next, you'll want to type in the following commands into either Terminal (on Mac) or cmd in Windows.

  • type npm init. Go through the menu prompts (doesn't really matter much). We need this to happen because it creates a package.json in the project root and because it creates a node-modules folder with all the fun stuff we want to use in our project.
  • The names of the packages you want are: (they're all listed here too: http://babeljs.io/docs/plugins/)
    • babel-cli installs Babel
    • babel-preset-latest preset to transpile the latest/most-recent JS abilities to ES5
  • Now you can install all the rest of the stuff you want with one command, like this: -
  • npm install --save-dev babel-cli babel-preset-latest
  • Or one at a time, each with npm install --save-dev in the front, followed by the npm package.
  • (the --save-dev writes each package name and its to the package.json file we created, aaannnd that's important for some reason.

Now to make sure it works correctly for your project, do this:

Create a new file entitled .babelrc at your project root. This is our config file for Babel. Now put in the preset and plugins you want in the following format: { "presets": ["latest"], "plugins": ["syntax-flow", "transform-flow-comments"] } (see https://babeljs.io/docs/plugins/#plugin-preset-paths for more details.)

And that's it! You have a transpiler on your system! And probably the best one too.

##Post 2

###How to set up ESLint in your project

In my opinion ESLint is probably the best "linter" of all the linters for JavaScript, but honestly almost any of them will do a really good job (like JSHint or JSLint).

A linter is basically like the famed IntelliSense on Visual Studio, which highlights your code and yaps at you like a little dog to tell you what's wrong with it. Yappy little dogs are actually pretty annoying, so that probably wasn't the best analogy.

Anyway, to set it up you gotta use the Node Package Manager or (npm), which has a pretty simple installation and can be found quickly online.

After installing npm, you need to navigate to your project root in a command line interface like Terminal on Macs, or cmd on windows.

(some of this is gonna be repeat from another post I did. Sorry!)

  • type npm init. Go through the menu prompts (doesn't really matter much). We need this to happen because it creates a package.json in the project root and because it creates a node-modules folder with all the fun stuff we want to use in our project.
  • Next, type npm install --save-dev eslint to install eslint to your project root. It should install pretty fast.
  • Now you need to initialize ESLint for your project. To do this type eslint --init in the command line interface.
  • A little menu will come up. You could easily just set it up with the settings you want to make it yell at you for placing semicolons for example, or you could just follow Google's Style Guide (or even AirBnb [what??]), or just the standard ESLint style guide.

Now ESLint is installed! You will most likely need to install a corresponding plugin of some sort to work with your text editor or IDE of choice. Every one I'm aware of has an ESLint plugin/extension, including:

  • Visual Studio Code (Microsoft's lightweight text editor, not the full-blown Visual Studio)
  • Atom (Github's editor)
  • Sublime Text
  • Webstorm
  • and probably a few others.

Anyway, that's it! Enjoy ESLint! It's super useful!

possibly use reactJS

-definitely use ECMA6, transpile with Babel

Welcome to Week 07 Cameron!

We’ve reached the mid-point of the semester. Please keep up the good work!

James 5:11 Behold, we count them happy which endure. "He that holds out faithful to the end shall in no wise lose his reward.” - Joseph Smith

DHTML

The title of this week is DHTML. I had never heard this phrase before teaching this class. For as long as I have been doing web development, this has been the way pages are built. We as users have come to expect it. The page should look good, we should get the quick feed back and interaction that comes via javascript. Anything less and the end user is disappointed. This is what marketing teams pay for. It is also how the web has moved beyond being a digital billboard and into an ecosystem where anything can be accomplished.

Overview

This week is an opportunity to bring together everything you have learned in the previous 5 weeks. You will be building a web page with HTML, styling it with CSS, using the Design principles to make it user friendly, and coding JavaScript to dynamically change the HTML and CSS.

After this week we will be turning to more back-end technologies such as XML and JSON (used to pass data around between servers and between clients and servers), AJAX (the mechanism for sending and receiving data in a format such as JSON from the server), and PHP (a server-side programming language which is often on the receiving end of AJAX calls).

Overview of This Week's Assignments

Prepare

  • The normal reading and quiz.

Teach One Another

  • This assignment will be a whole class discussion like last week.
  • Please keep posting until you have 100 points.

Ponder

  • This week you will be creating a simple e-commerice website. This website will be used again in Week 12 when you will be building the backend functionality for your website using PHP. You might want to read through the Week 12 Ponder assignment as you work on your website this week so that you will have everything ready for that assignment.
  • The form must include the following:
    • First name - You can validate that they entered something.
    • Last name - You can validate that they entered something.
    • Address - Fortunately you created a generic function last week to validate states, though you could choose to put the states into a drop-down/select element instead. For the zip code you could just validate that they entered 5 numbers. For the other text inputs you could validate that they entered anything.
    • Phone number - In the past some students have validated the phone number to check that it is in a specific format such as (123)446-7890 or 123-456-7890 but then their error validation is a generic message like “You did not enter the phone number in the correct format.” When that happens the only way I can figure out what the correct format I should enter is to look at the JavaScript! Please do not do this. You could either show on example on the screen of what format you are expecting and/or have the validation error message display what the correct format should be.
    • Shopping cart - Include the items' description, price, maybe an image, and some way to indicate which and perhaps how many of each item the user wishes to purchase.
    • Total - the total amount could update dynamically as the person is choosing what they want to purchase, or you could add a Total button that would update the total amount on the screen.
    • Payment information - Fortunately you created a generic function last week to validate credit card numbers. You might want to display the credit card types in a drop-down/select element. You also created a function last week for validating dates that you can probably repurpose for validating the credit card expiration date.
    • Submit and Reset - You are required to use the onSubmit and onReset events this week. I would suggest that you have the submit button display an alert that the form has been “submitted”. As mentioned above, in week 12 you will be making the submit button function so that the form data can be sent to the server. The reset button should reset (clear) the form elements.
    • 15 points to your Teach One Another Assignment if you send me an email stating you read my announcement.
  • You are required to use other events such as onClick, onBlur, and onLoad. I would recommend that you have both the onLoad and onReset call the same JavaScript function to reset/clear the form elements. I would recommend you use onInput instead of onBlur to validate the form elements. You could use the onClick event with checkboxes in the Shopping Cart or with a Total button.
  • You are required to put your JavaScript functions into an external JavaScript file.
  • Please remember that it is not only the functionality that matters, but also the design. Your page should both look good and be functional.

The Stateless Web (optional reading)

HTML is stateless. What this mean is that it does not maintain state in between pages. An example of state might be items a user has purchased which you might be storing in a JavaScript object. If the user goes to another web page, the new web page will not have any access to the JavaScript object from the previous page.

There are a number of ways to deal with the statelessness of HTML.

  1. SPA - Single Page Application - basically a website only has 1 page (which maintains state since you never go to another page) and the look/feel of the page is change via JavaScript and DOM manipulation.
  2. Store data in cookies or web storage. This maintains the data only for that browser on that particular computer (and, in the case of web storage, only for that particular browser tab). If the user goes to a different browser (or a different tab in the case of web storage) or a different computer then none of their data will be available.
  3. Store data on the server, perhaps in a database. The web pages can communicate with the server via AJAX, which we will learn about in a coming week.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment