{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# JavaScript Tutorial\n", "> Quick launch into Variables, Functions, Arrays, Classes, HTML.\n", "\n", "- layout: default\n", "- badges: false\n", "- permalink: /techtalk/javascript\n", "- image: /images/javascript.png\n", "- categories: [1.A, 3.B, C4.0]\n", "- type: pbl\n", "- week: 33" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "{% include nav_frontend.html %}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## JavaScript and Jupyter references\n", "> JavaScript is the most important language you need to learn as a frontend developer. Jupyter Notebooks is a convenient way to learn the language without the overhead of creating a full Website. Jupyter Notebooks had ChatGPT plugins to assist with design and troubleshooting problems. This Notebook has colors on HTML pages that were designed with a dark mode background.\n", "\n", "- JavaScript / Jupyter General References\n", " - [W3Schools JS Reference](https://www.w3schools.com/js/)\n", " - ChatGPT AI assistant for [Chrome/Jupyter](https://chrome.google.com/webstore/detail/chatgpt-jupyter-ai-assist/dlipncbkjmjjdpgcnodkbdobkadiejll) \n", " - Theme setup for Jupyter [Article](https://linuxhint.com/change-theme-jupyter-notebook/). Or do these commands from shell...\n", " - Install pip: pip install jupyterthemes\n", " - Revert to original theme: jt -r \n", " - List themes: jt -l\n", " - Install with Theme, Name, Logo: jt -t onedork -T -N -kl\n", " - [Chrome Dev Tools](https://developer.chrome.com/docs/devtools/)\n", "\n", "- Coding with jQuery\n", " - Jupyter Notebook [GitHub](https://github.com/nighthawkcoders/APCSP/blob/master/_notebooks/2022-09-19-PBL-javascript_tutorial.ipynb), wget: https://raw.githubusercontent.com/nighthawkcoders/APCSP/master/_notebooks/2022-09-19-PBL-javascript_tutorial.ipynb\n", " - Markdown [Fetch example](https://nighthawkcoders.github.io/APCSP/frontend/jquery) in GitHub project for [APCSP](https://github.com/nighthawkcoders/APCSP/blob/master/_posts/2023-06-01-jquery-sort.md)\n", " - HTML [Static example](https://flask.nighthawkcodingsociety.com/table/) in GitHub project for [flask_portfolio](https://github.com/nighthawkcoders/flask_portfolio/blob/main/templates/table.html)\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### output using HTML and CSS\n", " Multiple cells are used to setup HTML in this lesson. Many of the JavaScript cells will use the output tag(s) to write into the HTML that has been setup. \n", "- %%html is used to setup HTML code block\n", "- \"style\" tag enables visuals customization\n", "- \"div\" tag is setup to receive data" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", "
\n", " Hello!\n", "
\n", " \n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "\n", " \n", " \n", " \n", " \n", "
\n", " Hello!\n", "
\n", " \n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### output explored\n", "There are several ways to ouput the classic introduction message: \"Hello, World!\" \n", "- Before you go further, open Console on your Browser. JavaScript developer leaves Console open all the time!!!\n", "- The function console.log() outputs to Console, this is often used for inspection or debugging.\n", "- \"Hello, World\" is a String literal. This is the referred to as Static text, as it does not change. Developer call this a hard coded string.\n", "- \"Hello, World\" literal is a parameter to console.log(), element.txt() and alert().\n", "- The element.txt function is part of Jupyter Notebook %%js magic. This is convenient for Notebook and testing.\n", "- The alert command outputs the parameter to a dialog box, so you can see it in this Jupyter notebook. The alert commands are shown, but are commented out as the stop run all execution of the notebook.\n", "- Note, in a Web Application Debugging: An alert is often used for less savy Developers. Console is used by more savy developers; console often requires setting up a lot of outputs. Source level debugging is the most powerful solution for debugging and does not require alert or console commands." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "application/javascript": [ "console.log(\"JavaScript/Jupyter Output Intro\");\n", "\n", "// Browser Console output; debugging or tracing\n", "console.log(\"Hello, World!\");\n", "console.log(\"Hello, World Again!\");\n", "\n", "// Document Object Model (DOM) output; output to HTML, CSS which is standard for a Web Page\n", "// select element method: DOM native JavaScript get, document.getElementByID\n", "document.getElementById(\"output\").textContent = \"Hello, World!\";\n", "// jQuery CSS-style method: Tag for DOM selector, $('#output')\n", "$('#output').append('
Hello World Again!'); // br is break or new line, b is bold\n", "\n", "// Jupyter built in magic element for testing and convenience of development\n", "element.text(\"Hello, World!\"); // element is output option as part of %%js magic\n", "element.append('
Hello World Again!');\n", "\n", "//alert(\"Hello, World!\");\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%js // required to allow cell to be JavaScript enabled\n", "console.log(\"JavaScript/Jupyter Output Intro\");\n", "\n", "// Browser Console output; debugging or tracing\n", "console.log(\"Hello, World!\");\n", "console.log(\"Hello, World Again!\");\n", "\n", "// Document Object Model (DOM) output; output to HTML, CSS which is standard for a Web Page\n", "// select element method: DOM native JavaScript get, document.getElementByID\n", "document.getElementById(\"output\").textContent = \"Hello, World!\";\n", "// jQuery CSS-style method: Tag for DOM selector, $('#output')\n", "$('#output').append('
Hello World Again!'); // br is break or new line, b is bold\n", "\n", "// Jupyter built in magic element for testing and convenience of development\n", "element.text(\"Hello, World!\"); // element is output option as part of %%js magic\n", "element.append('
Hello World Again!');\n", "\n", "//alert(\"Hello, World!\");" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### multiple outputs using one variable\n", "This second example is a new sequence of code, two or more lines of code forms a sequence. This example defines a variable, thank goodness!!! In the previous example we were typing the string `\"Hello, World\" over and over`. Observe with the variable `msg=\"Hello, World!\";` we type the string once and now use `msg` over and over.\n", "- The variable \"var msg =\" is used to capture the data\n", "- The console.log(msg) outputs to console, be sure to Inspect it!\n", "- The element.text() is part of Jupyter Notebooks and displays as output blow the code on this page. Until we build up some more interesting data for Web Site, we will not use be using the Python HTML, CSS technique.\n", "- The alert(msg) works the same as previous, but as the other commands uses msg as parameter." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [ { "data": { "application/javascript": [ "console.log(\"Variable Definition\");\n", "\n", "var msg = \"Hello, World!\";\n", "\n", "// Use msg to output code to Console and Jupyter Notebook\n", "console.log(msg); //right click browser select Inspect, then select Console to view\n", "element.text(msg);\n", "//alert(msg);\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%js\n", "console.log(\"Variable Definition\");\n", "\n", "var msg = \"Hello, World!\";\n", "\n", "// Use msg to output code to Console and Jupyter Notebook\n", "console.log(msg); //right click browser select Inspect, then select Console to view\n", "element.text(msg);\n", "//alert(msg);\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### output showing use of a function\n", "This example passes the defined variable \"msg\" to the newly defined \"function logIt(output)\".\n", "- There are multiple steps in this code..\n", " - The \"definition of the function\": \"function logIt(output) {}\" and everything between curly braces is the definitions of the function. Passing a parameter is required when you call this function.\n", " - The \"call to the function:\"logIt(msg)\" is the call to the function, this actually runs the function. The variable \"msg\" is used a parameter when calling the logIt function.\n", "- Showing reuse of function...\n", " - There are two calls to the logIt function\n", " - This is called Prodedural Abstraction, a term that means reusing the same code" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [ { "data": { "application/javascript": [ "console.log(\"Function Definition\");\n", "\n", "/* Function: logIt\n", " * Parameter: output\n", " * Description: The parameter is \"output\" to console and jupyter page\n", "*/\n", "function logIt(output) {\n", " console.log(output); \n", " element.append(output + \"
\");\n", " //alert(output);\n", "}\n", "\n", "// First sequence calling logIt function\n", "var msg = \"Hello, World!\";\n", "logIt(msg);\n", "\n", "// Second sequence calling logIt function\n", "var msg = \"Hello, Students!\" // replaces content of variable\n", "var classOf = \"Welcome CS class of 2023-2024.\"\n", "logIt(msg + \" \" + classOf); // concatenation of strings\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%js\n", "console.log(\"Function Definition\");\n", "\n", "/* Function: logIt\n", " * Parameter: output\n", " * Description: The parameter is \"output\" to console and jupyter page\n", "*/\n", "function logIt(output) {\n", " console.log(output); \n", " element.append(output + \"
\");\n", " //alert(output);\n", "}\n", "\n", "// First sequence calling logIt function\n", "var msg = \"Hello, World!\";\n", "logIt(msg);\n", "\n", "// Second sequence calling logIt function\n", "var msg = \"Hello, Students!\" // replaces content of variable\n", "var classOf = \"Welcome CS class of 2023-2024.\"\n", "logIt(msg + \" \" + classOf); // concatenation of strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### output showing Loosely typed data\n", "JavaScript is a loosely typed language, meaning you don't have to specify what type of information will be stored in a variable in advance. \n", "- To define a variable you prefix the name with var or const. The variable type is determined by JavaScript at runtime.\n", "- Python and many interpretive languages are loosely typed like JavaScript. This is considered programmer friendly. \n", "- Java which is a compiled language is strongly typed, thus you will see terms like String, Integer, Double, and Object in the source code. \n", "- In JavaScript, the typeof keyword returns the type of the variable. Become familiar with type as it is valuable in conversation and knowing type help you understand how to modify data. Each variable type will have built in methods to manage content within the data type." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [ { "data": { "application/javascript": [ "console.log(\"Examine Data Types\");\n", "\n", "// Function to add typeof to output\n", "function getType(output) {\n", " return typeof output + \": \" + output;\n", "}\n", "\n", "// Function defintion\n", "function logIt(output) {\n", " console.log(getType(output)); // logs string\n", " console.info(output); // logs object\n", " element.append(getType(output) + \"
\"); // adds to Jupyter output\n", " //alert(getType(output));\n", "}\n", "\n", "// Common Types\n", "element.append(\"Common Types
\");\n", "logIt(\"Mr M\"); // String\n", "logIt(1997); // Number\n", "logIt(true); // Boolean\n", "element.append(\"
\");\n", "\n", "// Object Type, this definition is often called a array or list\n", "element.append(\"Object Type, array
\");\n", "var scores = [\n", " 90,\n", " 80, \n", " 100\n", "]; \n", "logIt(scores);\n", "element.append(\"
\");\n", "\n", "// Complex Object, this definition is often called hash, map, hashmap, or dictionary\n", "element.append(\"Object Type, hash or dictionary
\");\n", "var person = { // key:value pairs seperated by comma\n", " \"name\": \"Mr M\", \n", " \"role\": \"Teacher\"\n", "}; \n", "logIt(person);\n", "logIt(JSON.stringify(person)); //method used to convert this object into readable format\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%js\n", "console.log(\"Examine Data Types\");\n", "\n", "// Function to add typeof to output\n", "function getType(output) {\n", " return typeof output + \": \" + output;\n", "}\n", "\n", "// Function defintion\n", "function logIt(output) {\n", " console.log(getType(output)); // logs string\n", " console.info(output); // logs object\n", " element.append(getType(output) + \"
\"); // adds to Jupyter output\n", " //alert(getType(output));\n", "}\n", "\n", "// Common Types\n", "element.append(\"Common Types
\");\n", "logIt(\"Mr M\"); // String\n", "logIt(1997); // Number\n", "logIt(true); // Boolean\n", "element.append(\"
\");\n", "\n", "// Object Type, this definition is often called a array or list\n", "element.append(\"Object Type, array
\");\n", "var scores = [\n", " 90,\n", " 80, \n", " 100\n", "]; \n", "logIt(scores);\n", "element.append(\"
\");\n", "\n", "// Complex Object, this definition is often called hash, map, hashmap, or dictionary\n", "element.append(\"Object Type, hash or dictionary
\");\n", "var person = { // key:value pairs seperated by comma\n", " \"name\": \"Mr M\", \n", " \"role\": \"Teacher\"\n", "}; \n", "logIt(person);\n", "logIt(JSON.stringify(person)); //method used to convert this object into readable format" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Build a Person object and JSON\n", "JavaScript and other languages have special properties and syntax to store and represent data. In fact, a class in JavaScript is a special function.\n", "\n", "- Definition of class allows for a collection of data, the \"class Person\" allows programmer to retain name, github id, and class of a Person.\n", "- Instance of a class, the \"const teacher = new Person(\"Mr M\", \"jm1021\", 1977)\" makes an object \"teacher\" which is an object representation of \"class Person\".\n", "- Setting and Getting properties After creating teacher and student objects, observe that properties can be changed/muted or extracted/accessed." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Classroom JSON Data
{\"classroom\":[{\"type\":\"object\",\"name\":\"sample\",\"ghID\":\"sample\",\"classOf\":2000,\"role\":\"sample\"}]}
\n", "\n", " \n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Classroom JSON Data
{\"classroom\":[{\"type\":\"object\",\"name\":\"sample\",\"ghID\":\"sample\",\"classOf\":2000,\"role\":\"sample\"}]}
\n", "\n", " \n", "" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [ { "data": { "application/javascript": [ "console.log(\"Person objects\");\n", "\n", "/* class: Person\n", " * Description: A collection of Person data\n", "*/\n", "class Person {\n", " /* method: constructor\n", " * parameters: name, ghID - GitHub ID, classOf - Graduation Class \n", " * description: returns object when \"new Person()\" is called with matching parameters\n", " * assignment: this.name, this.ghID, ... are properties retained in the returned object\n", " * default: role uses a default property, it is set to \"Student\"\n", " */\n", " constructor(name, ghID, classOf, role=\"Student\") {\n", " this.name = name;\n", " this.ghID = ghID;\n", " this.classOf = classOf;\n", " this.role = role;\n", " }\n", "\n", " /* method: setter\n", " * parameters: role - role in classroom\n", " * description: this.role is updated from default value to value contained in role parameter\n", " */\n", " setRole(role) {\n", " this.role = role;\n", " }\n", " \n", " /* method: getter\n", " * description: turns properties of object into JSON object\n", " * return value: JSON object\n", " */\n", " getJSON() {\n", " const obj = {type: typeof this, name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};\n", " const json = JSON.stringify(obj);\n", " return json;\n", " }\n", "\n", " /* method: logIT\n", " * description: \"this\" Person object is logged to console\n", " */\n", " logIt() {\n", " //Person Object\n", " console.info(this);\n", " //Log to Jupter\n", " element.append(\"Person object in JSON
\");\n", " element.append(this.getJSON() + \"
\"); \n", " //alert(this.getJSON());\n", " }\n", " \n", "}\n", "\n", "// make a new Person Object\n", "const teacher = new Person(\"Mr M\", \"jm1021\", 1977); // object type is easy to work with in JavaScript\n", "// update role to Teacher\n", "teacher.setRole(\"Teacher\"); // set the role\n", "teacher.logIt(); // log to console\n", "\n", "// make a new Person Object\n", "const student = new Person(\"Jane Doe\", \"jane\", 2007); // object type is easy to work with in JavaScript\n", "student.logIt(); // log to console\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%js\n", "console.log(\"Person objects\");\n", "\n", "/* class: Person\n", " * Description: A collection of Person data\n", "*/\n", "class Person {\n", " /* method: constructor\n", " * parameters: name, ghID - GitHub ID, classOf - Graduation Class \n", " * description: returns object when \"new Person()\" is called with matching parameters\n", " * assignment: this.name, this.ghID, ... are properties retained in the returned object\n", " * default: role uses a default property, it is set to \"Student\"\n", " */\n", " constructor(name, ghID, classOf, role=\"Student\") {\n", " this.name = name;\n", " this.ghID = ghID;\n", " this.classOf = classOf;\n", " this.role = role;\n", " }\n", "\n", " /* method: setter\n", " * parameters: role - role in classroom\n", " * description: this.role is updated from default value to value contained in role parameter\n", " */\n", " setRole(role) {\n", " this.role = role;\n", " }\n", " \n", " /* method: getter\n", " * description: turns properties of object into JSON object\n", " * return value: JSON object\n", " */\n", " getJSON() {\n", " const obj = {type: typeof this, name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};\n", " const json = JSON.stringify(obj);\n", " return json;\n", " }\n", "\n", " /* method: logIT\n", " * description: \"this\" Person object is logged to console\n", " */\n", " logIt() {\n", " //Person Object\n", " console.info(this);\n", " //Log to Jupter\n", " element.append(\"Person object in JSON
\");\n", " element.append(this.getJSON() + \"
\"); \n", " //alert(this.getJSON());\n", " }\n", " \n", "}\n", "\n", "// make a new Person Object\n", "const teacher = new Person(\"Mr M\", \"jm1021\", 1977); // object type is easy to work with in JavaScript\n", "// update role to Teacher\n", "teacher.setRole(\"Teacher\"); // set the role\n", "teacher.logIt(); // log to console\n", "\n", "// make a new Person Object\n", "const student = new Person(\"Jane Doe\", \"jane\", 2007); // object type is easy to work with in JavaScript\n", "student.logIt(); // log to console" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Build a Classroom Array/List of Persons and JSON\n", "Many key elements are shown again. New elements include...\n", "- Building an Array, \"var students\" is an array of many persons\n", "- Building a Classroom, this show forEach iteration through an array and .push adding to an array. These are key concepts in all programming languages." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [ { "data": { "application/javascript": [ "console.log(\"Classroom object\");\n", "\n", "/* class: Person\n", " * Description: A collection of Person data\n", "*/\n", "class Person {\n", " /* method: constructor\n", " * parameters: name, ghID - GitHub ID, classOf - Graduation Class \n", " * description: returns object when \"new Person()\" is called with matching parameters\n", " * assignment: this.name, this.ghID, ... are properties retained in the returned object\n", " * default: this.role is a default property retained in object, it is set to \"Student\"\n", " */\n", " constructor(name, ghID, classOf, role=\"Student\") {\n", " this.name = name;\n", " this.ghID = ghID;\n", " this.classOf = classOf;\n", " this.role = role;\n", " }\n", "\n", " /* method: setter\n", " * parameters: role - role in classroom\n", " * description: this.role is updated from default value to value contained in role parameter\n", " */\n", " setRole(role) {\n", " this.role = role;\n", " }\n", " \n", " /* method: getter\n", " * description: turns properties of object into JSON object\n", " * return value: JSON object\n", " */\n", " getJSON() {\n", " const obj = {type: typeof this, name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};\n", " const json = JSON.stringify(obj);\n", " return json;\n", " }\n", "\n", " /* method: logIT\n", " * description: \"this\" Person object is logged to console\n", " */\n", " logIt() {\n", " //Person Object\n", " console.info(this);\n", " //Log to Jupter\n", " element.append(\"Person json
\");\n", " element.append(this.getJSON() + \"
\"); \n", " //alert(this.getJSON());\n", " }\n", " \n", "}\n", "\n", "/* class: Classroom\n", " * Description: A collection of Person objects\n", "*/\n", "class Classroom {\n", " /* method: constructor\n", " * parameters: teacher - a Person object, students - an array of Person objects\n", " * description: returns object when \"new Classroom()\" is called containing properties and methods of a Classroom\n", " * assignment: this.classroom, this.teacher, ... are properties retained in the returned object\n", " */\n", " constructor(teacher, students) {\n", " /* spread: this.classroom contains Teacher object and all Student objects\n", " * map: this.json contains of map of all persons to JSON\n", " */\n", " this.teacher = teacher;\n", " this.students = students;\n", " this.classroom = [teacher, ...students]; // ... spread option\n", " this.json = '{\"classroom\":[' + this.classroom.map(person => person.getJSON()) + ']}';\n", " }\n", "\n", " /* method: logIT\n", " * description: \"this\" Classroom object is logged to console\n", " */\n", " logIt() {\n", " //Classroom object\n", " console.log(this);\n", " \n", " //Classroom json\n", " element.append(\"Classroom object in JSON
\");\n", " element.append(this.json + \"
\"); \n", " //alert(this.json);\n", " }\n", "}\n", "\n", "/* function: constructCompSciClassroom\n", " * Description: Create data for Classroom and Person objects\n", " * Returns: A Classroom Object\n", "*/\n", "function constructCompSciClassroom() {\n", " // define a Teacher object\n", " const teacher = new Person(\"Mr M\", \"jm1021\", 1977, \"Teacher\"); // optional 4th parameter\n", "\n", " // define a student Array of Person objects\n", " const students = [ \n", " new Person(\"Anthony\", \"tonyhieu\", 2022),\n", " new Person(\"Bria\", \"B-G101\", 2023),\n", " new Person(\"Allie\", \"xiaoa0\", 2023),\n", " new Person(\"Tigran\", \"Tigran7\", 2023),\n", " new Person(\"Rebecca\", \"Rebecca-123\", 2023),\n", " new Person(\"Vidhi\", \"VidhiKulkarni\", 2024)\n", " ];\n", "\n", " // make a CompSci classroom from formerly defined teacher and student objects\n", " return new Classroom(teacher, students); // returns object\n", "}\n", "\n", "// assigns \"compsci\" to the object returned by \"constructCompSciClassroom()\" function\n", "const compsci = constructCompSciClassroom();\n", "// output of Objects and JSON in CompSci classroom\n", "compsci.logIt();\n", "// enable sharing of data across jupyter cells\n", "$('#jsonText').text(compsci.json); // posts/embeds/writes compsci.json to HTML DOM element called jsonText\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%js\n", "console.log(\"Classroom object\");\n", "\n", "/* class: Person\n", " * Description: A collection of Person data\n", "*/\n", "class Person {\n", " /* method: constructor\n", " * parameters: name, ghID - GitHub ID, classOf - Graduation Class \n", " * description: returns object when \"new Person()\" is called with matching parameters\n", " * assignment: this.name, this.ghID, ... are properties retained in the returned object\n", " * default: this.role is a default property retained in object, it is set to \"Student\"\n", " */\n", " constructor(name, ghID, classOf, role=\"Student\") {\n", " this.name = name;\n", " this.ghID = ghID;\n", " this.classOf = classOf;\n", " this.role = role;\n", " }\n", "\n", " /* method: setter\n", " * parameters: role - role in classroom\n", " * description: this.role is updated from default value to value contained in role parameter\n", " */\n", " setRole(role) {\n", " this.role = role;\n", " }\n", " \n", " /* method: getter\n", " * description: turns properties of object into JSON object\n", " * return value: JSON object\n", " */\n", " getJSON() {\n", " const obj = {type: typeof this, name: this.name, ghID: this.ghID, classOf: this.classOf, role: this.role};\n", " const json = JSON.stringify(obj);\n", " return json;\n", " }\n", "\n", " /* method: logIT\n", " * description: \"this\" Person object is logged to console\n", " */\n", " logIt() {\n", " //Person Object\n", " console.info(this);\n", " //Log to Jupter\n", " element.append(\"Person json
\");\n", " element.append(this.getJSON() + \"
\"); \n", " //alert(this.getJSON());\n", " }\n", " \n", "}\n", "\n", "/* class: Classroom\n", " * Description: A collection of Person objects\n", "*/\n", "class Classroom {\n", " /* method: constructor\n", " * parameters: teacher - a Person object, students - an array of Person objects\n", " * description: returns object when \"new Classroom()\" is called containing properties and methods of a Classroom\n", " * assignment: this.classroom, this.teacher, ... are properties retained in the returned object\n", " */\n", " constructor(teacher, students) {\n", " /* spread: this.classroom contains Teacher object and all Student objects\n", " * map: this.json contains of map of all persons to JSON\n", " */\n", " this.teacher = teacher;\n", " this.students = students;\n", " this.classroom = [teacher, ...students]; // ... spread option\n", " this.json = '{\"classroom\":[' + this.classroom.map(person => person.getJSON()) + ']}';\n", " }\n", "\n", " /* method: logIT\n", " * description: \"this\" Classroom object is logged to console\n", " */\n", " logIt() {\n", " //Classroom object\n", " console.log(this);\n", " \n", " //Classroom json\n", " element.append(\"Classroom object in JSON
\");\n", " element.append(this.json + \"
\"); \n", " //alert(this.json);\n", " }\n", "}\n", "\n", "/* function: constructCompSciClassroom\n", " * Description: Create data for Classroom and Person objects\n", " * Returns: A Classroom Object\n", "*/\n", "function constructCompSciClassroom() {\n", " // define a Teacher object\n", " const teacher = new Person(\"Mr M\", \"jm1021\", 1977, \"Teacher\"); // optional 4th parameter\n", "\n", " // define a student Array of Person objects\n", " const students = [ \n", " new Person(\"Anthony\", \"tonyhieu\", 2022),\n", " new Person(\"Bria\", \"B-G101\", 2023),\n", " new Person(\"Allie\", \"xiaoa0\", 2023),\n", " new Person(\"Tigran\", \"Tigran7\", 2023),\n", " new Person(\"Rebecca\", \"Rebecca-123\", 2023),\n", " new Person(\"Vidhi\", \"VidhiKulkarni\", 2024)\n", " ];\n", "\n", " // make a CompSci classroom from formerly defined teacher and student objects\n", " return new Classroom(teacher, students); // returns object\n", "}\n", "\n", "// assigns \"compsci\" to the object returned by \"constructCompSciClassroom()\" function\n", "const compsci = constructCompSciClassroom();\n", "// output of Objects and JSON in CompSci classroom\n", "compsci.logIt();\n", "// enable sharing of data across jupyter cells\n", "$('#jsonText').text(compsci.json); // posts/embeds/writes compsci.json to HTML DOM element called jsonText" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### for loop to generate Table Rows in HTML output\n", "This code extracts JSON text from HTML, that was placed in DOM in an earlier JavaScript cell, then it parses text into a JavaScript object. In addition, there is a for loop that iterates over the extracted object generating formated rows and columns in an HTML table.\n", "\n", "- Table generation is broken into parts...\n", " - table data is obtained from a classroom array inside of the extracted object. \n", " - the JavaScript for loop allows the construction of a new row of data for each Person hash object inside of the the Array.\n", " - in the loop a table row ` ... ` is created for each Hash object in the Array.\n", " - in the loop table data, a table column, ` ... ` is created for name, ghID, classOf, and role within the Hash object." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "vscode": { "languageId": "javascript" } }, "outputs": [ { "data": { "application/javascript": [ "console.log(\"Classroom Web Page\");\n", "\n", "// extract JSON text from HTML page\n", "const jsonText = document.getElementById(\"jsonText\").innerHTML;\n", "console.log(jsonText);\n", "element.append(\"Raw jsonText element embedded in HTML
\");\n", "element.append( jsonText + \"
\");\n", "\n", "// convert JSON text to Object\n", "const classroom = JSON.parse(jsonText).classroom;\n", "console.log(classroom);\n", "\n", "// from classroom object creates rows and columns in HTML table\n", "element.append(\"
Formatted data sample from jsonText
\");\n", "for (var row of classroom) {\n", " element.append(row.ghID + \" \" + row.name + '
');\n", " // tr for each row, a new line\n", " $('#classroom').append('')\n", " // td for each column of data\n", " $('#classroom').append('' + row.name + '')\n", " $('#classroom').append('' + row.ghID + '')\n", " $('#classroom').append('' + row.classOf + '')\n", " $('#classroom').append('' + row.role + '')\n", " // tr to end row\n", " $('#classroom').append('');\n", "}\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%js\n", "console.log(\"Classroom Web Page\");\n", "\n", "// extract JSON text from HTML page\n", "const jsonText = document.getElementById(\"jsonText\").innerHTML;\n", "console.log(jsonText);\n", "element.append(\"Raw jsonText element embedded in HTML
\");\n", "element.append( jsonText + \"
\");\n", "\n", "// convert JSON text to Object\n", "const classroom = JSON.parse(jsonText).classroom;\n", "console.log(classroom);\n", "\n", "// from classroom object creates rows and columns in HTML table\n", "element.append(\"
Formatted data sample from jsonText
\");\n", "for (var row of classroom) {\n", " element.append(row.ghID + \" \" + row.name + '
');\n", " // tr for each row, a new line\n", " $('#classroom').append('')\n", " // td for each column of data\n", " $('#classroom').append('' + row.name + '')\n", " $('#classroom').append('' + row.ghID + '')\n", " $('#classroom').append('' + row.classOf + '')\n", " $('#classroom').append('' + row.role + '')\n", " // tr to end row\n", " $('#classroom').append('');\n", "}" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IDNameDOBAge
\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "\n", " \n", " \n", " \n", " \n", " \n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
IDNameDOBAge
\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Hacks\n", "> One key to these hacks is to build confidence with me going into final grade, I would like to see each student adapt this frontend work in their final project. Second key is the finished work can serve as review for the course, notes for the future in relationship to frontend.\n", "- Adapt this tutorial to your own work\n", "- Consider what you need to work on to be stronger developer\n", "- Show something creative or unique, no cloning\n", "- Be ready to talk to Teacher for 5 to 10 minutes. Individually!!!\n", "- Show in Jupyter Notebook during discussion, show Theme and ChatGPT\n", "- Have a runtime final in GithHub Pages (or Fastpage)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.12" } }, "nbformat": 4, "nbformat_minor": 2 }