Show Menu

WebApps Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.


Full stack: Browser <=> Webserver <=> Database system MEAN stack (Angular, Node, Express, MongoDB)


Web browsers display Documents described in HTML. Use JavaScript to dynami­cally generate and update documents. Include directives with content (annotate with tags). Tags: formatting info, meaning of text, additional info to display Malformed html: complain or figure out missing tag and continue processing Document: hierar­chical collection of elements Tags can have attributes Entities: &lt; &g; &amp; &quot;   <p> <br> <h1­>, <b> <i> <pr­e> (typically used for code, spaces signif­icant) <im­g> <a href=“­”> <ta­ble> <tr> <td> <ul> <li> <ol> <li> <di­v> (group related elements, where the group occupies entire lines, forces a line break before and after) <sp­an> Grouping related elements, group is within a single line <fo­rm> <in­put> <te­xta­rea> <se­lec­t> HTML and XHTML differ­ence: can skip some end tags, not all attributes have to have values (<s­elect multip­le> elements can overlap


http:/­/ho­st.c­om­pan­y.c­om:­80/­a/b­/c.h­tm­l?u­ser­=Al­ice­&y­ear­=20­08#p2 Scheme (http:): identifies protocol used to fetch the content. http: is the most common scheme; it means use the HTTP protocol https: is similar to http: except that it uses SSL encryption file: means read a file from the local disk mailto: means open an email program composing a message Host name (//hos­t.c­omp­ name of a machine to connect to. Server's port number (80): allows multiple servers to run on the same machine. Hierar­chical portion (/a/b/­c.h­tml): used by server to find content. Web server programmed with routing inform­ation. Map hierar­chical position to function to be performed and possibly the function's parameters Query parameters (?user­=Al­ice­&y­ear­=2008): provides additional parameters Fragment (#p2): Have browser scroll page to fragment (html: p2 is anchor tag) Type of Links Full URL: <a href="h­ttp­://­www.xy­z.c­om/­new­s/2­­ml">2009 News</­a> Absolute URL: <a href="/­sto­ck/­quo­te.h­tm­l"> same as http:/­/ww­w.x­yz.c­om­/st­ock­/qu­ote.html Relative URL (intra­-site links): <a href="2­008­/Ma­­ml"> same as http:/­/ww­w.x­yz.c­om­/ne­ws/­200­8/M­arc­h.html Define an anchor point (a position that can be referenced with # notation): <a name="s­ec3­"> Go to a different place in the same page: <a href="#­sec­3"> Users of URLs Loading a page, loading an image, spread­sheet, embed a page: <iframe src="ht­tp:­//w­ww.g­oo­­m"> URL encoding must be repres­ented as %xx, where xx is the hexade­cimal value of the character: URI vs URL A URL is a type of URI. But that doesn’t mean all URIs are URLs. The part that makes a URI a URL is the inclusion of the “access mechan­ism”, or “network location”, e.g. http:// or ftp://.


Template HTML with additional markup used to describe what should be displayed Directive Allows developer to extend HTML with own elements and attributes (reusable pieces) Scope Context where the model data is stored so that templates and contro­llers can access Compiler Processes the template to generate HTML for the browser Data Binding Syncing of the data between the Scope and the HTML (two ways) Dependency Injection Fetching and setting up all the functi­onality needed by a component Module A container for all the parts of an applic­ation Service A way of packaging functi­onality to make it available to any view Controller: angula­r.m­odu­le(­"­cs1­42A­pp", []) .contr­oll­er(­'My­Cntrl', functi­on(­$scope) { $scope.yo­urName = "­"; $­eeting = "­Hol­a"; }); Each template component gets a new scope and is paired with a contro­ller. A scope object gets its prototype set to its enclosing parent scope. Dot in your model: Model reads will go up to fetch properties from inherited scopes. Writes will create the property in the current scope! Scope digest and watches: Two-way binding works by watching when expres­sions in view template change and updating the corres­ponding part of the DOM. Angular add a watch for every variable or function in template expres­sions. Compared to previous values during digest proces­sing. Add your own watches: ($scop­e.$­wat­ch(­'fi­rst­Name', functi­on())) (e.g. caching in contro­ller) Trigger a digest cycle: ($scop­e.$­dig­est()) (e.g. model updates in event) ngRepeat: <li ng-rep­eat­="person in people­Arr­ay". ng-if: Include in DOM if expression true. (will create scope/­con­tro­llers when true, exit goint to false) ng-show: Like ngIf except uses visibility to hide/show DOM elements. Occupies space in DOM structure (but not on screen) when hidden. Scope & contro­llers created at startup. ng-click: run code when element clicked. ngModel: Bind with input, select, textarea tags. ng-href, ng-src. ng-include: <div ng-inc­lud­e="'­nav­Bar­Hea­­ml'­"­</d­iv>. Directives: Package together HTML template and Controller and extend templating language. Be inserted by HTML compiler as: attribute (<div my-dir­="fo­o">...<­/di­v>) or element (<m­y-dir arg1="f­oo">...<­/m­y-d­ir>). Specify the template and controller to use. Accept arguments from the template. Run as a child scope or isolated scope Services: Used to provide code modules across view compon­ents. $http, $resource, $xhrFa­ctory, $location, $window, $document, $timeout, $interval. Dependency injection: var cs142App = angula­r.m­odu­le(­'cs­142­App', ['ngRo­ute']); cs142A­pp.c­on­fig­(['­$ro­ute­Pro­vider', functi­on(­$ro­ute­Pro­vider) { cs142A­pp.c­on­tro­lle­r('­Mai­nCo­ntr­oller', ['$sco­pe'­,fu­nct­ion­($s­cope) {. Angular APIs: ngRoute - Client­-side URL routing and URL manage­ment, ngResource (REST API access), ngCookies, ngAria (Support for people with disabi­lit­ies), ngTouch, ngAnimate, ngSanitize (parse and manipulate HTML) safely.


Types: Mouse-­rel­ated: mouse movement, button click, enter/­leave element, keyboa­rd-­rel­ated: down, up, press, Focus-­rel­ated: focus in, focus out (blur), Input field changed, Form submitted, Timer events. Event handling:: <div onclic­k="g­otM­ous­eCl­ick­('i­d42'); gotMou­se=­tru­e;">...<­/d­iv>; elemen­t.o­nclick = mouseC­lick; elemen­t.a­ddE­ven­tLi­ste­ner­("cl­ick­", mouseC­lick); Event object: subclassed MouseE­vent, Keyboa­rdE­vent. type, timestamp, curren­tTarget (element that listener was registered on), target (element that dispatched the event). MouseEvent: button, pageX, pageY (mouse position relative to the top-left corner of document), screenX, screenY (mouse position in screen coordi­nates). Keyboa­rdEvent: keyCode, charCode (integer unicode, if there is one). Draggable rect; elem.s­tyl­e.left = (elem.o­ff­setLeft + (event.pageX - prevX)) + "­px"; Capture phase: Start at the outermost element and work down to the innermost nested element. ○ Each element can stop the capture, so that its children never see the even event.s­to­pPr­opa­gat­ion(). elemen­t.a­ddE­ven­tLi­ste­ner­(ev­ent­Type, handler, true); Bubble phase: Most on handlers (e.g. onclick) use bubble, not onfocu­s/blur. Invoke handlers on the innermost nested element that dispatches the event (mostly right thing). Timeout: setTim­eou­t(m­yFunc, 5*1000), setInt­erv­al(­myfunc, 50), clearI­nte­rva­l(t­oken). Event processed one-at­-a-time: Does not interleave with other js execution. Handlers run to comple­tion, no multit­hre­ading.

Single Page Applic­ations

Browser tosses current JS enviro­nment when navigating to a different page: Typing into location bar or forwar­d/back buttons. Selecting a bookmarked URL, page refesh, assign­ments to window.lo­cation. Can change hash fragment and query parameters without reload. Deep linking: the URL should capture the web app's context so that directing the browser to the URL will result the app's execution to that context. Two approaches: maintain the app's context state in the URL, provide a share button to generate deep linking URL. ngRoute: A directive (ngView) to indicate where view components should be inserted in template. A service ($route) that watches window.lo­cation for changes and updates the displayed view. A config­uration ($rout­ePr­ovider) that allows the user to specify the mappings of URLs to view compon­ents. <div ng-vie­w><­/di­v>. angula­r.m­odu­le(­'cs­142­App', ['ngRo­ute']). cs142A­pp.c­on­fig­(['­$ro­ute­Pro­vider', functi­on(­$ro­ute­Pro­vider) { $route­Pro­vid­er.w­he­n('­/Bo­ok/­:bo­okId', { templa­teUrl: 'book.h­tml', contro­ller: 'BookC­ont­rol­ler'}). Passing parame­ters**: $route­Par­­okId.


Separate style from content body { -> selector margin: 8px; property, value Selectors: Tag name: h1, class attribute: .large, Tag and class: p.large, Element id #p20 Pseudo selectors: p: hover, a:link, a:visited Color: color and backgr­oun­d_color rgb(255, 255, 0) Box model Margin -> border -> padding -> element (width, height) Total element width: width + left padding + right padding + left border + right border + left margin + right margin Distance units: Absolute: 2px, 1mm, 2cm, 0.2in, 3pt 2m (2 times the element’s current font size, 2rem (2 times the root element’s current font size) border­-bo­tto­m-c­olo­r/s­tyl­e/width Position: position: static; (default) - Position in document flow
position: relative; Position relative to default position via top, right, bottom, and left properties
position: fixed; Position to a fixed location on the screen via top, right, bottom, and left properties
position: absolute; Position relative to ancestor absolute element via top, right, bottom, and left properties
backgr­oun­d-i­mage, backgr­oun­d-r­epeat, font, font-f­amily, font-size, font-w­eight, font-s­tyle, text-a­lign, vertic­al-­align, cursor (eg. help) display: none (element not displayed, and takes no space in layout) display: inline display: block visibi­lity: hidden (element is hidden but space still alloca­ted­)|v­isible font-size inherited, border, background not inherited Most specific rule wins <link rel=“s­tyl­esheet” type=“­tex­t/css” href=“­myS­tyl­es.css” />

Javacript basics

high-l­evel, dynamic, untyped, and interp­reted progra­mming language ... is protot­ype­-based with first-­class functions, … ... supporting object­-or­iented, impera­tive, and functional progra­mming
Need to define variables, variables have the type of the last thing assigned to it. Undefined, number, string, boolean, function, object.
Two scopes: Global and function local. All var statements hoisted to top of scope.
Number: NaN, infinity, bitwise operators 32 bit. String: indexOf(), charAt(), match(), search(), replace(), toUppe­rCa­se(), toLowe­rCa­se(), slice(), substr() boolean: false, 0, "­", null, undefined, and NaN undefined and null: null - a value that represents whatever the user wants it to Use to return special condition (e.g. no value) typeof null == ‘object’ Both are falsy but not equal (null == undefined; null !== undefined) functions: arguments array. All functions return a value (default is undefi­ned). first class functions: can be passed as arguments, returned, stored. Object: Object is an unordered collection of name-value pairs called proper­ties. Name can be any string. or bar["na­me"].­nEx­istent == undefined. Global scope object in browser (windo­w[p­rop]). To remove proper­ties, use delete. delete Arrays: Objects. Can be sparse and polymo­rphic. push, pop, shift, unshift, sort, reverse, splice. Can store properties like objects. Dates: var date = new Date(). number of ms since midnight Jan 1st, 1970 UTC. valueO­f(),, toISOS­tri­ng(), toLoca­leS­tri­ng(). Regular Expres­sions: var re = /ab+c/; or var re2 = new RegExp­("ab­+c"). String: search(), match(), replace(), split(). RegExp: exec() and test().
/HALT/.te­st(­str); // Returns true if string str has the substr HALT
/halt/­i.t­est­(str); // Same but ignore case
/[Hh]alt [A-Z]/.te­st(­str); // Returns true if str either “Halt L” or “halt L”
'XXX abbbbb­bc'.se­arc­h(/­ab+c/); // Returns 4 (position of ‘a’)
'XXX ac'.se­arc­h(/­ab+c/); // Returns -1, no match
'XXX ac'.se­arc­h(/abc/); // Returns 4
'12e34­'.s­ear­ch(/[\d]/); // Returns 2
'foo: bar;'.s­ea­rch­(/...\s
:\s...\s;/); // Returns 0
var str = "This has 'quoted' words like 'this'­";
var re = /'[']'/g;
re.exe­c(str); // Returns ["'q­uot­ed'­", index: 9, input:
re.exe­c(str); // Returns ["'t­his­'", index: 29, input: …
re.exe­c(str); // Returns null­tch(/'[']
'/g); // Returns ["'q­uot­ed'­", "­'th­is'­"]­pla­ce(/'[']*'/g, 'XXX'); // Returns:
'This has XXX words with XXX.'
try, catch, finally. <script type="t­ext­/ja­vas­cri­pt" src="co­de.j­s">­</s­cri­pt>

Front End Progra­mming

CGI: Certain URLs map to executable programs that generate web page. Templates: mix code and HTML. Write HTML document containing parts of the page that are always the same. Add bits of code that generate the parts that are computed for each page.Object­-re­lat­ional mapping: simplify the use of databases (make database tables and rows appear as classes and objects). Model View Controller: Model: manages the applic­ation's data, view: HTML/CSS, contro­ller: fetch models and control view, handle user intera­tcions. AngularJS view template: Hello {{models.user.firstName}}. Angular controller: Angular creates $scope and calls controller function called when view is instan­tiated. Angular data: REST APIs and JSON. Mongoos's ODL: var userSchema = new Schema({ firstName: String, lastName: String, }); var User = mongoo­se.m­od­el(­'User', userSc­hema);

Responsive Web Apps

Add grid layout system with relative rathen than absolute measures. Add @media rules based on screen sizes. Made images support relative sizes. @media only screen and (min-w­idth: 768px){ / tablets and desktop layout / } @media only screen and (max-w­idth: 767px) {/ phones / } @media only screen and (max-w­idth: 767px) and (orien­tation: portrait) { / portrait phones / }. Use CSS breakp­oints to control layout and functi­onality: Layout altern­atives, App functi­onality condit­ional on available screen real estate.

Javascript Progra­mming

OOP: In methods this will be bound to the object.­ys(­this). In non-method functions, this is the global object or undefined if strict. Functions can have properties too. plus1.i­nv­oca­tions. Classes: var r = new Rectan­gle(26, 14). Prototypes: Prototype objects can have prototype objects forming a prototype chain. On an object property read access JavaScript will search the up the prototype chain until the property is found. The properties of an object are its own property in addition to all the properties up the prototype chain. This is called protot­ype­-based inheri­tance. Property updates always create property in object. Rectan­­oto­typ­e.area = function() {}. Object.keys() would return width and height. Functional: can write entire program as functions with no side effects. Closures: For private properties var myObj = (funct­ion() { var privat­eProp1 = 1; var privat­eProp2 = "­tes­t"; var setPri­vate1 = functi­on(­val1) { privat­eProp1 = val1; } var compute = function() {return privat­eProp1 + privat­ePr­op2;} return {compute: compute, setPri­vate1: setPri­vate1}; })(); typeof myObj; // 'object'­ys(­myObj); // [ 'compute', 'setPr­ivate1' ] Fix for fileNo: Make fileno an argument. printF­ile­Len­gth­(fi­leNo); JSON: JSON.s­tri­ngi­fy(obj) or JSON.p­ars­e(s).
Bad parts: Declares variables on use. Automatic semicolon insertion - Workar­ound: Enforce semicolons with checkers. Type coercing equals: ==. Always use ===, !==. ("" == "­0") is false but (0 == "­") is true, so is (0 == '0') (false == '0') is true as is (null == undefi­ned).Assign default value: hostname = hostname || "­loc­alh­ost­";. Access an undefined object property: var prop = obj &&­opn­ame;. Handle multiple this. var self = this; fs.rea­dFi­le(­sel­f.f­ileName + fileNo, function (err, data) { consol­e.l­og(­sel­f.f­ile­Nam­e,f­ileNo); });


window, this. Rooted at­cum­ent.head. nodeName property is element type (uppercase P, DIV, etc.) or #text. parent­Node, nextSi­bling, prevSi­bling, firstC­hild, lastChild. Can do elemen­t.s­etA­ttr­ibute. By id docume­nt.g­et­Ele­men­tBy­Id(­"­div­42"), getEle­men­tsB­yCl­ass­Name(), getEle­men­tsB­yTa­gNa­me(). textCo­ntent: text content of a node and its descen­dants. innerHTML: HTML syntax describing the element's descen­dants. outerHTML same but includes element. getAtt­rib­ute­()/­set­Att­rib­ute(). elemen­t.i­nne­rHTML = "This text is <i>­imp­ort­ant­</i­>", replaces content but retains attrib­utes. elemen­t.s­tyl­e.d­isplay = "­non­e", image.src = "­new­Ima­ge.j­pg­". elemen­t.c­las­sName = "­act­ive­"; docume­nt.c­re­ate­Ele­men­t("P­"), docume­nt.c­re­ate­Tex­tNode. parent.ap­pen­dCh­ild­(el­ement); or­ser­tBe­for­e(e­lement, sibling), node.r­emo­veC­hil­d(o­ldN­ode); Redirect to new page: window.lo­cat­ion.href = "­new­Pag­e.h­tml­". DOM Coordinate System: The screen origin is at the upper left; y increases as you go down. The position of an element is determined by the upper-left outside corner of its margin. Read location with elemen­t.o­ffs­etLeft, elemen­t.o­ffs­etTop. Coordi­nates are relative to elemen­t.o­ffs­etP­arent, which is not necess­arily the same as elemen­t.p­are­ntNode. Default offset­Parent is the body element. Position explicity: Absolute the element no longer occupies space in document flow. The origin inside an offset­Parent (for positi­oning descen­dants) is just inside the upper-left corner of its border. Absolute: explicitly positi­oned, relative element is positioned automa­tically the usual way. This element will become the offset­Parent for all its descen­dants unless overri­dden. Dimensions: Reading dimens­ions: elemen­t.o­ffs­etWidth and elemen­t.o­ffs­etH­eight Include contents, padding, border, but not margin. Updating dimens­ions: elemen­t.s­tyl­e.width and elemen­t.s­tyl­e.h­eight. If you want child to be positioned wrt to you, you should be relative, child should be absolute.

Building web applic­ations

Be consis­tent, provide context, be fast. Style guide: covers the look and feel of the app. style, user intera­ctions, layout. Design templates: Master­-detail template. Front-­end­-fr­ame­works (boots­trap) css style sheets, html components (buttons, menus, toolbars, lists, table, forms), javascript (modals, transi­tions, dropdo­wns). <md­-to­olb­ar> layout­="ro­w" flex>. <md­-co­nte­nt> contents can be the ng-view directive.
Angular Material responsive support: <md­-button hide-g­t-sm... <md­-menu show-lg .. <md­-si­denav md-is-­loc­ked­-op­en=­"­$md­Med­ia(­'gt­-sm­')". On mobile: md-is-­loc­ked­-op­en=­"­$md­Med­ia(­'gt­-sm­')". Make a button in the toolbar for opening the nav bar <md­-button hide-gt-sm ng-cli­ck=­"­tog­gle­Use­rLi­st(­)" > <md­-icon md-svg­-ic­on=­"­men­u" ></­md-­ico­n><­/md­-bu­tto­n>t­ogg­leU­serList = function() { $mdSid­ena­v("u­ser­s").t­og­gle(); }. ARIA: Add text descri­ptions for things that need it <a aria-l­abe­l="Photo of user {{}}". Intern­ati­ona­liz­ation: <h1>{{i18n.GettingStarted}}</h1> <h1 transl­ate­>Ge­tting Starte­d</­h1> <h1>{{"Getting Starte­d" | transl­ate­}}<­/h1­>. Testing: Unit testing, each test targets a particular component. Requires mock compon­ents. e2e testing: Run tests against the real web applic­ation. Scripting interface into browser used to drive web applic­ation. Example: Fire up app in a browser and progra­mma­tically interact with it. WebDriver interface in browsers useful for this.